|
| 1 | +#include <iostream> |
| 2 | +#include <cmath> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +void print2D(int arr[][20], int M, int N) { |
| 6 | + for (int i = 0; i < M; ++i) { |
| 7 | + for (int j = 0; j < N; ++j) { |
| 8 | + cout << arr[i][j] << " "; |
| 9 | + } |
| 10 | + cout << endl; |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +bool myfixed[20][20] = {}; |
| 15 | + |
| 16 | +void input2D_soduku(int arr[][20], int M, int N) |
| 17 | +{ |
| 18 | + for (int i = 0; i < M; ++i) |
| 19 | + { |
| 20 | + for (int j = 0; j < N; ++j) |
| 21 | + { |
| 22 | + cin >> arr[i][j]; |
| 23 | + if (arr[i][j] != 0) myfixed[i][j] = true; //so that our entry does not change |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +bool canPlace(int board[][20], int N, int x, int y, int num) |
| 29 | +{ |
| 30 | + //check along row && col |
| 31 | + for (int i = 0; i < N; ++i) |
| 32 | + { |
| 33 | + if (board[x][i] == num) return false; //check along row |
| 34 | + if (board[i][y] == num) return false; //check along col |
| 35 | + } |
| 36 | + |
| 37 | + //check in the box |
| 38 | + int rootN = sqrt(N); |
| 39 | + int boxRow = x / rootN; |
| 40 | + int boxCol = y / rootN; |
| 41 | + int startRow = boxRow * rootN; |
| 42 | + int startCol = boxCol * rootN; |
| 43 | + |
| 44 | + for (int r = startRow; r < startRow + rootN; ++r) |
| 45 | + { |
| 46 | + for (int c = startCol; c < startCol + rootN; ++c) |
| 47 | + { |
| 48 | + if (board[r][c] == num) return false; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return true; |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +bool solveSudoku(int board[][20], int N, int x, int y) |
| 57 | +{ |
| 58 | + if (x == N && y == 0) return true; //we have reached row 4 ---->sudoku over |
| 59 | + |
| 60 | + if (y == N) return solveSudoku(board, N, x + 1, 0);//stop y to go to column4-->goto nxt row |
| 61 | + |
| 62 | + if (myfixed[x][y]) return solveSudoku(board, N, x , y + 1); |
| 63 | + |
| 64 | + for (int num = 1; num <= N; ++num) |
| 65 | + { |
| 66 | + if (canPlace(board, N, x, y, num) == true) |
| 67 | + { |
| 68 | + board[x][y] = num; |
| 69 | + bool isSuccessful = solveSudoku(board, N, x , y + 1); //recursion for nxt columns |
| 70 | + if (isSuccessful) return true; |
| 71 | + else board[x][y] = 0; |
| 72 | + } |
| 73 | + } |
| 74 | + return false; |
| 75 | +} |
| 76 | + |
| 77 | +int main() |
| 78 | +{ |
| 79 | + int board[20][20] = {}; |
| 80 | + |
| 81 | + int N; |
| 82 | + cin >> N; |
| 83 | + input2D_soduku(board, N, N); |
| 84 | + for(int i=0;i<N;i++){ |
| 85 | + for(int j=0;j<N;j++){ |
| 86 | + cin>>board[i][j]; |
| 87 | + } |
| 88 | + } |
| 89 | + cout << "==============\n"; |
| 90 | + |
| 91 | + print2D(board, N, N); |
| 92 | + |
| 93 | + cout << "==============\n"; |
| 94 | + |
| 95 | + solveSudoku(board, N, 0, 0); |
| 96 | + |
| 97 | + print2D(board, N, N); |
| 98 | + |
| 99 | +} |
| 100 | + |
0 commit comments