📢 공지합니다
이 게시글은 메인 페이지에 항상 고정되어 표시됩니다.
https://www.acmicpc.net/problem/2239

package bra;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Bra2239 {
static int[][] board = new int[9][9];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 입력 받기
for (int i = 0; i < 9; i++) {
String line = br.readLine();
for (int j = 0; j < 9; j++) {
board[i][j] = line.charAt(j) - '0';
}
}
solve(0, 0);
}
// (row, col) 위치부터 채우기 시작
private static void solve(int row, int col) {
if (col == 9) {
solve(row + 1, 0);
return;
}
if (row == 9) {
// 끝내기
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sb.append(board[i][j]);
}
sb.append("\n");
}
System.out.println(sb.toString().trim());
System.exit(0);
}
if (board[row][col] == 0) {
for (int num = 1; num <= 9; num++) {
if (valid(row, col, num)) {
board[row][col] = num;
solve(row, col + 1);
board[row][col] = 0;
}
}
} else {
solve(row, col + 1);
}
}
private static boolean valid(int row, int col, int num) {
// 가로 세로
for (int i = 0; i < 9; i++) {
if (board[row][i] == num) return false;
if (board[i][col] == num) return false;
}
// 3*3
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == num) return false;
}
}
return true;
}
}
재미있게 풀었던 문제이다. 핵심은 System.exit가 중요하다. 바로 끝내야한다. return 하면 시간초과가 나버린다.
| [백준 10942번] 팰린드롬? || [백준 1509번] 팰린드롬 분할 (0) | 2025.09.21 |
|---|---|
| [백준 17404번] RGB거리 2 (0) | 2025.09.17 |
| [백준 1647번] 도시 분할 계획 || [백준 20040번] 사이클 게임 || [백준 2252번] 줄 세우기 || 음악 프로그램 (0) | 2025.09.15 |
| [백준 22251번] 빌런 호석 (0) | 2025.09.14 |
| [백준 2668번] 숫자고르기 || [백준 9466번] 텀 프로젝트 (0) | 2025.09.11 |