-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsudoku.cpp
More file actions
89 lines (84 loc) · 1.93 KB
/
sudoku.cpp
File metadata and controls
89 lines (84 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define n 9
bool isSafeRow(int board[n][n], int row, int num){
for(int i = 0; i < n; i++){
if(board[row][i] == num){
return false;
}
}
return true;
}
bool isSafeCol(int board[n][n], int col, int num){
for(int i = 0; i < n; i++){
if(board[i][col] == num){
return false;
}
}
return true;
}
bool isSafeGrid(int board[n][n], int row, int col, int num){
int rowf = row - (row%3);
int colf = col - (col%3);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(board[i+rowf][j+colf] == num){
return false;
}
}
}
return true;
}
bool isSafe(int board[n][n], int row, int col, int num){
if(isSafeRow(board, col, num && isSafeCol(board, row, num) && isSafeGrid(board, row, col, num))){
return true;
}
return false;
}
bool findEmptySpace(int board[n][n], int &row, int &col){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(board[i][j] == 0){
row = i;
col = j;
return false;
}
}
}
return true;
}
bool solveSudoku(int board[n][n]){
int row, col;
if(!findEmptySpace(board, row, col)){
return true;
}
for(int i = 1; i <= 9; i++){
if(isSafe(board, row, col, i)){
board[row][col] = i;
if(solveSudoku(board)){
return true;
}
board[row][col] = 0;
}
}
}
int main()
{
int board[9][9];
for(int i = 0; i < n; i++){
string s;
cin>> s;
for(int j = 0; j < n; j++){
board[i][j] = s[j] - '0';
}
}
solveSudoku(board);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cout<<board[i][j];
}
cout<<endl;
}
return 0;
}