Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2d279dc

Browse files
committed
sudoku
1 parentf5bc05b commit2d279dc

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

‎hash/SolveSudoku.java

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
packageAlgorithms.hash;
2+
3+
publicclassSolveSudoku {
4+
publicvoidsolveSudoku(char[][]board) {
5+
dfs(board,0,0);
6+
}
7+
8+
publicbooleandfs(char[][]board,intx,inty) {
9+
// go to next row.
10+
if (y ==9) {
11+
y =0;
12+
x++;
13+
}
14+
15+
// done
16+
if (x >=9) {
17+
returntrue;
18+
}
19+
20+
// Skip the solved point.
21+
if (board[x][y] !='.') {
22+
returndfs(board,x,y +1);
23+
}
24+
25+
// Go throught all the possibilities.
26+
for (intk =0;k <9;k++) {
27+
board[x][y] = (char)('1' +k);
28+
// SHOULD RETURN HERE IF INVALID.
29+
if (isValid(board,x,y) &&dfs(board,x,y +1)) {
30+
returntrue;
31+
}
32+
board[x][y] ='.';
33+
}
34+
35+
// because all the possibility is impossiable.
36+
returnfalse;
37+
}
38+
39+
publicbooleanisValid(char[][]board,intx,inty) {
40+
// Judge the column.
41+
for (inti =0;i <9;i++) {
42+
if (i !=x &&board[i][y] ==board[x][y]) {
43+
returnfalse;
44+
}
45+
}
46+
47+
// Judge the row.
48+
for (inti =0;i <9;i++) {
49+
if (i !=y &&board[x][i] ==board[x][y]) {
50+
returnfalse;
51+
}
52+
}
53+
54+
// Judge the block.
55+
inti =x /3 *3;
56+
intj =y /3 *3;
57+
for (intk =0;k <9;k++) {
58+
intxIndex =i +k /3;
59+
intyIndex =j +k %3;
60+
if (xIndex ==x &&yIndex ==y) {
61+
continue;
62+
}
63+
64+
if (board[xIndex][yIndex] ==board[x][y]) {
65+
returnfalse;
66+
}
67+
}
68+
69+
returntrue;
70+
}
71+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp