From ad1722323a01b7cc772965764bbe2d7ffcc30d14 Mon Sep 17 00:00:00 2001 From: songyc macbook Date: Mon, 10 Nov 2025 21:15:00 +0900 Subject: [PATCH] 20251110 baekjoon --- code_study/Baekjoon/java/_2239.java | 70 +++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 code_study/Baekjoon/java/_2239.java diff --git a/code_study/Baekjoon/java/_2239.java b/code_study/Baekjoon/java/_2239.java new file mode 100644 index 0000000..34a9d25 --- /dev/null +++ b/code_study/Baekjoon/java/_2239.java @@ -0,0 +1,70 @@ +import java.util.*; + +public class _2239 { + static int[][] board = new int[9][9]; + static int[][] empties = new int[81][2]; + static int empties_count = 0; + + static boolean isPossible(int x, int y, int n) { + for(int i=0; i<9; i++) { + if(board[y][i] == n && i != x) return false; + if(board[i][x] == n && i != y) return false; + + int nx = (x/3)*3 + i%3; + int ny = (y/3)*3 + i/3; + if(board[ny][nx] == n && !(nx==x && ny==y)) return false; + } + + return true; + } + + static void printBoard() { + for(int[] row : board) { + for(int n : row) { + System.out.printf("%d", n); + } + System.out.printf("\n"); + } + } + + static void backTracking(int depth) { + if(depth == empties_count) { + printBoard(); + System.exit(0); + } + + int cx = empties[depth][0]; + int cy = empties[depth][1]; + + for(int n=1; n<=9; n++) { + if(isPossible(cx, cy, n)) { + board[cy][cx] = n; + backTracking(depth+1); + board[cy][cx] = 0; + } + } + + return; + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + for(int i=0; i<9; i++) { + board[i] = sc.nextLine().chars() + .map(c->c-'0') + .toArray(); + + for (int j=0; j<9; j++) { + if(board[i][j]==0) { + empties[empties_count][0] = j; + empties[empties_count][1] = i; + empties_count++; + } + } + } + + sc.close(); + + backTracking(0); + } +} \ No newline at end of file