-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudoku.java
More file actions
141 lines (103 loc) · 3.33 KB
/
Sudoku.java
File metadata and controls
141 lines (103 loc) · 3.33 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
public class Sudoku {
public static void main(String[] args){
String [] ss = {"..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."};
char[][] board = new char[9][];
for(int i =0; i<9; i++){
board[i] = ss[i].toCharArray();
}
for(int i=0;i<9;i++){
for(int j=0; j<9;j++){
System.out.print(board[i][j]);
}
System.out.print('\n');
}
solveSudoku(board);
for(int i=0;i<9;i++){
for(int j=0; j<9;j++){
System.out.print(board[i][j]);
}
System.out.print('\n');
}
}
public static void solveSudoku(char[][] board) {
// Start typing your Java solution below
// DO NOT write main() function
solveSudoku(board,-1,-1);
}
public static char[][] solveSudoku(char[][] board, int x, int y){
int i=0;
int j=0;
int posx =x;
int posy = y;
boolean find =false;
if(x<0||y<0){
for(i =0; i<9;i++){
for(j=0;j<9;j++){
if(board[i][j]=='.'&&find==false){
posx = i;
posy = j;
find = true;
break;
}
}
if(find == true){
break;
}
}
}
while(board[posx][posy] !='9'){
if(board[posx][posy]=='.'){
board[posx][posy] = '1';
}else if (board[posx][posy]>='1'&&board[posx][posy]<'9'){
board[posx][posy]+=1;
}
if(checkPartial(board, posx, posy)==true){
find =false;
for(i =0; i<9;i++){
for(j=0;j<9;j++){
if(board[i][j]=='.'&&find==false){
find = true;
break;
}
}
if(find == true){
break;
}
}
if(i==9&&j==9){
return board;
}
else{
char[][] temp = solveSudoku(board, i, j);
if(temp == null){
continue;
}else {
return temp;
}
}
}
}
board[posx][posy]='.';
return null;
}
public static boolean checkPartial(char[][] board, int posx, int posy){
for(int i =0; i<9; i++){
if(i!=posx&&board[i][posy]==board[posx][posy]){
return false;
}
}
for(int j=0; j<9; j++){
if(j!=posy&&board[posx][j]==board[posx][posy]){
return false;
}
}
for(int i=posx/3*3;i<posx/3*3+3;i++){
for(int j= posy/3*3;j<posy/3*3+3;j++){
if(i!=posx&&j!=posy&&board[i][j]==board[posx][posy]){
return false;
}
}
}
return true;
}
}