Problem Link
Detailed Step-by-Step Explanation
Solution 1: https://leetcode.com/problems/valid-sudoku/solutions/7463671/smartest-way-to-solve-most-optimal-uniqu-b8z4
Solution 2: https://leetcode.com/problems/valid-sudoku/solutions/7463665/most-optimal-solution-beats-200-n-hashse-bukb
Solution 1
class Solution {
public boolean isValidSudoku(char[][] board) {
Set<String> set = new HashSet<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char current = board[i][j];
if (current == '.') continue;
String rowKey = current + "_in_row_" + i;
String colKey = current + "_in_column_" + j;
String boxKey = current + "_in_box_" + (i / 3) + "_" + (j / 3);
if (set.contains(rowKey) || set.contains(colKey) || set.contains(boxKey)) {
return false;
}
set.add(rowKey);
set.add(colKey);
set.add(boxKey);
}
}
return true;
}
}
Solution 2
class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[][] rows = new boolean[9][9];
boolean[][] cols = new boolean[9][9];
boolean[][] boxes = new boolean[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') continue;
int num = board[i][j] - '1';
int boxIndex = (i / 3) * 3 + (j / 3);
if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
return false;
}
rows[i][num] = true;
cols[j][num] = true;
boxes[boxIndex][num] = true;
}
}
return true;
}
}

Top comments (0)