2025-11-10 21:15:00 +09:00

70 lines
1.7 KiB
Java

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);
}
}