Solve Sudoku (Backtracking)?
Short answer: bool SolveSudoku(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { Follow on: if (board[i][j] == '.') { for (char c = '1'; c <= '9'; c++) { if (IsValid(board, i, j, c)) { board[i][j] = c; if (SolveSudoku(board)) return true; else board[i][j] = '.'; } } return false; } } } return true; } bool IsValid(char[][] board, int row, int col, char c) { for (int i = 0; i < 9; i++) { if…
Explain a bit more
(board[row][i] == c) return false; if (board[i][col] == c) return false; if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; } return true; } Explanation: Backtracking tries digits 1-9 in empty cells, validating constraints.
Example code
bool SolveSudoku(char[][] board) {
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{ Follow on: if (board[i][j] == '.')
{
for (char c = '1'; c <= '9'; c++)
{
if (IsValid(board, i, j, c))
{
board[i][j] = c;
if (SolveSudoku(board))
return true; else board[i][j] = '.';
}
}
return false;
}
}
}
return true;
} bool IsValid(char[][] board, int row, int col, char c) {
for (int i = 0; i < 9; i++)
{
if (board[row][i] == c) return false;
if (board[i][col] == c) return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; }
return true;
} Explanation: Backtracking tries digits 1-9 in empty cells, validating constraints.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png