Skip to content

Commit 708abe2

Browse files
authored
[20250716] BOJ / G4 / 스도쿠 / 이준희
1 parent ca90421 commit 708abe2

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.InputStreamReader;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
import java.util.StringTokenizer;
7+
8+
public class Main {
9+
static int[][] board = new int[9][9]; // 스도쿠판
10+
static boolean[][] row = new boolean[9][10]; // row[a][b] = a번째 줄에 b가 있는지
11+
static boolean[][] col = new boolean[9][10]; // col[a][b] = a번째 칸에 b가 있는지
12+
static boolean[][] box = new boolean[9][10]; // box[a][b] = a번째 박스에 b가 있는지
13+
static List<int[]> blanks = new ArrayList<>(); // 빈칸 위치
14+
static boolean solved = false; // 풀었는지 안풀었는지
15+
16+
public static void main(String[] args) throws Exception {
17+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
18+
StringTokenizer st;
19+
20+
for (int i = 0; i < 9; i++) {
21+
String str = br.readLine();
22+
for (int j = 0; j < 9; j++) {
23+
int num = str.charAt(j) - '0';
24+
board[i][j] = num;
25+
if (num == 0) {
26+
blanks.add(new int[]{i, j});
27+
} else { // 입력하면서 있는지에 대한 처리
28+
row[i][num] = true;
29+
col[j][num] = true;
30+
box[(i / 3) * 3 + (j / 3)][num] = true;
31+
}
32+
}
33+
}
34+
35+
dfs(0);
36+
}
37+
38+
static void dfs(int depth) {
39+
if (depth == blanks.size()) { // 풀었으면 끝
40+
StringBuilder sb = new StringBuilder();
41+
for (int[] line : board) {
42+
for (int num : line) {
43+
sb.append(num);
44+
}
45+
sb.append('\n');
46+
}
47+
System.out.print(sb);
48+
solved = true;
49+
return;
50+
}
51+
52+
int[] pos = blanks.get(depth); // 빈칸마다 탐색
53+
int x = pos[0];
54+
int y = pos[1];
55+
int boxnum = (x / 3) * 3 + (y / 3);
56+
57+
for (int num = 1; num <= 9; num++) { // 중복정답인경우 작은 수 출력이므로 1부터 시작
58+
if (!row[x][num] && !col[y][num] && !box[boxnum][num]) { // 수 검증
59+
row[x][num] = col[y][num] = box[boxnum][num] = true; // 방문 처리
60+
board[x][y] = num; // 입력
61+
62+
dfs(depth + 1);
63+
if (solved) return;
64+
65+
board[x][y] = 0; // 백트래킹
66+
row[x][num] = col[y][num] = box[boxnum][num] = false;
67+
}
68+
}
69+
}
70+
}
71+
72+
```

0 commit comments

Comments
 (0)