Skip to content

Commit c09e3f7

Browse files
committed
[Week06] BOJ 2580: 스도쿠
1 parent e329d03 commit c09e3f7

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package week06.BOJ_2580_스도쿠;
2+
import java.util.*;
3+
import java.lang.*;
4+
import java.io.*;
5+
6+
class BOJ2580 {
7+
static int N = 9;
8+
static int[][] board;
9+
public static void main(String[] args) throws IOException {
10+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
board = new int[N][N];
12+
for (int i = 0; i < N; i++) {
13+
StringTokenizer st = new StringTokenizer(br.readLine());
14+
for (int j = 0; j < N; j++) {
15+
board[i][j] = Integer.parseInt(st.nextToken());
16+
}
17+
}
18+
sudoku(0, 0);
19+
}
20+
21+
static void sudoku(int x, int y) {
22+
if (y == N) { //하나의 행 모두 확인
23+
sudoku(x + 1, 0); //다음 행으로 이동
24+
return;
25+
}
26+
27+
if (x == N) { //모든 칸 확인 -> 출력
28+
StringBuilder sb = new StringBuilder();
29+
for(int i = 0; i < N; i++){
30+
for(int j = 0; j < N; j++){
31+
sb.append(board[i][j]).append(' ');
32+
}
33+
sb.append("\n");
34+
}
35+
System.out.println(sb);
36+
System.exit(0); //하나만 출력해야하기 때문에 시스템 종료
37+
}
38+
39+
if (board[x][y] == 0) { //빈칸일 경우
40+
for (int num = 1; num <= N; num++) { //1~9 중 가능한 수 찾기
41+
if (checkPossible(x, y, num)) {
42+
board[x][y] = num; //가능한 수 빈칸에 넣기
43+
sudoku(x, y + 1); //다음 칸 확인
44+
board[x][y] = 0; //다시 빈 칸으로 처리
45+
}
46+
}
47+
} else { //빈칸이 아닐 경우 다음 칸 확인
48+
sudoku(x, y + 1);
49+
}
50+
}
51+
52+
static boolean checkPossible(int x, int y, int value) { //value가 있는지 검사
53+
//행 검사
54+
for (int i = 0; i < N; i++) {
55+
if (board[x][i] == value) {
56+
return false;
57+
}
58+
}
59+
60+
//열 검사
61+
for (int i = 0; i < N; i++) {
62+
if (board[i][y] == value) {
63+
return false;
64+
}
65+
}
66+
67+
//정사각형 검사
68+
int sx = (x / 3) * 3;
69+
int sy = (y / 3) * 3;
70+
for (int i = sx; i < sx + 3; i++) {
71+
for (int j = sy; j < sy + 3; j++) {
72+
if (board[i][j] == value) {
73+
return false;
74+
}
75+
}
76+
}
77+
return true;
78+
}
79+
80+
}

0 commit comments

Comments
 (0)