20251110 baekjoon
This commit is contained in:
parent
c3d11cc909
commit
ad1722323a
70
code_study/Baekjoon/java/_2239.java
Normal file
70
code_study/Baekjoon/java/_2239.java
Normal file
@ -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);
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user