Skip to content

Instantly share code, notes, and snippets.

@smothiki
Created January 7, 2024 17:00
Show Gist options
  • Save smothiki/6505f0ccb096e324a65ef7e73400719a to your computer and use it in GitHub Desktop.
Save smothiki/6505f0ccb096e324a65ef7e73400719a to your computer and use it in GitHub Desktop.
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<string> seen;
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.')
continue;
const string c(1, board[i][j]);
if (!seen.insert(c + "@row" + to_string(i)).second ||
!seen.insert(c + "@col" + to_string(j)).second ||
!seen.insert(c + "@box" + to_string(i / 3) + to_string(j / 3))
.second)
return false;
}
class Solution {
public void solveSudoku(char[][] board) {
dfs(board, 0);
}
private boolean dfs(char[][] board, int s) {
if (s == 81)
return true;
final int i = s / 9;
final int j = s % 9;
if (board[i][j] != '.')
return dfs(board, s + 1);
for (char c = '1'; c <= '9'; ++c)
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (dfs(board, s + 1))
return true;
board[i][j] = '.';
}
return false;
}
private boolean isValid(char[][] board, int row, int col, char c) {
for (int i = 0; i < 9; ++i)
if (board[i][col] == c || board[row][i] == c ||
board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)
return false;
return true;
}
}
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment