Skip to content

Commit 93769b4

Browse files
authored
Merge pull request #490 from AlgorithmWithGod/0224LJH
[20250717] BOJ / G4 / 스도쿠 / 이종환
2 parents 4f7b8f9 + 772dc42 commit 93769b4

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed

0224LJH/202507/17 BOJ 스도쿠.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.Arrays;
6+
7+
public class Main {
8+
static int[][] arr;
9+
static boolean finished = false;
10+
public static void main(String[] args) throws IOException {
11+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
arr = new int[9][9];
13+
for (int i = 0; i < 9; i++) arr[i] = Arrays.stream(br.readLine().split("")).mapToInt(Integer::parseInt).toArray();
14+
process();
15+
print();
16+
}
17+
18+
19+
20+
private static void print() {
21+
for (int i = 0; i<9; i++) {
22+
for (int j = 0; j < 9; j++) {
23+
System.out.print(arr[i][j]);
24+
}
25+
System.out.println();
26+
}
27+
}
28+
29+
private static void process() {
30+
int stY = -1;
31+
int stX = -1;
32+
33+
outer:
34+
for (int i = 0; i < 9; i++) {
35+
for (int j = 0; j < 9; j++) {
36+
if (arr[i][j] == 0) {
37+
stY = i;
38+
stX = j;
39+
break outer;
40+
}
41+
}
42+
}
43+
boolean[] nums = findAvailable(stY,stX);
44+
for (int i = 1; i <= 9; i++) {
45+
if (finished) return;
46+
if (!nums[i])continue;
47+
arr[stY][stX] = i;
48+
sudoku(stY,stX);
49+
50+
}
51+
52+
}
53+
54+
55+
private static void sudoku(int y, int x) {
56+
int ny = -1;
57+
int nx = -1;
58+
outer:
59+
for (int i = y; i < 9; i++) {
60+
for (int j = 0; j < 9; j++) {
61+
if(arr[i][j] != 0) continue;
62+
else {
63+
ny = i;
64+
nx = j;
65+
break outer;
66+
}
67+
}
68+
}
69+
if(ny == -1 && nx == -1) {
70+
finished = true;
71+
return;
72+
}
73+
74+
boolean[] nums = findAvailable(ny,nx);
75+
for (int i = 1; i <= 9; i++) {
76+
if (finished) return;
77+
if (!nums[i])continue;
78+
arr[ny][nx] = i;
79+
sudoku(ny,nx);
80+
if(!finished)arr[ny][nx] = 0;
81+
82+
}
83+
84+
}
85+
86+
private static boolean[] findAvailable(int stY, int stX) {
87+
boolean[] ans = new boolean[10];
88+
Arrays.fill(ans, true);
89+
for (int i = 0; i < 9; i++) {
90+
ans[arr[stY][i]] = false;
91+
ans[arr[i][stX]] = false;
92+
}
93+
94+
int pY = stY/3;
95+
int pX = stX/3;
96+
for (int i = pY*3; i < pY*3 + 3; i++) {
97+
for (int j = pX*3; j < pX*3+3; j++) {
98+
ans[arr[i][j]] = false;
99+
}
100+
}
101+
102+
return ans;
103+
}
104+
105+
106+
}
107+
108+
```

0 commit comments

Comments
 (0)