본문 바로가기
Algorithm/백준

[백준] 스도쿠 2580번 - java

by jackWillow 2021. 11. 2.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	
	private static int[][] table = new int[9][9];
	private static int[][] nullCell = new int[81][2];
	private static int n;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = null;
		n = 0;
		for(int i = 0; i < 9; i++) {
			st = new StringTokenizer(br.readLine());
			for(int j = 0; j < 9; j++) {
				table[i][j] = Integer.parseInt(st.nextToken());
				if(table[i][j] == 0) {
					nullCell[n][0] = i;
					nullCell[n++][1] = j;
				}
			}
		}
		sudoku(0);
		br.close();
	}
	
	private static void sudoku(int depth) {
		if(depth == n) {
			printSudoku();
			System.exit(0);
		}
		
		int x = nullCell[depth][0];
		int y = nullCell[depth][1];
		boolean[] exists = getPossibleNums(x, y);
		for(int j = 1; j < 10; j++) {
			if(!exists[j]) {
				table[x][y] = j;
				sudoku(depth + 1);
				table[x][y] = 0;
			}
		}
	}
	
	private static boolean[] getPossibleNums(int x, int y) {
		boolean[] exists = new boolean[10];
		for(int i = 0 ; i < 9; i++) {
			if(table[x][i] != 0) {
				int num = table[x][i];
				exists[num] = true;
			}
			if(table[i][y] != 0) {
				int num = table[i][y];
				exists[num] = true;
			}
		}
		
		int xi = (x / 3) * 3;
		int yi = (y / 3) * 3;
		for(int i = xi; i < xi + 3; i++) {
			for(int j = yi; j < yi + 3; j++) {
				if(table[i][j] != 0) {
					int num = table[i][j];
					exists[num] = true;
				}
			}
		}
		
		return exists;
	}
	
	private static void printSudoku() {
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < 9; i++) {
			for(int j = 0; j < 9; j++) {
				sb.append(table[i][j]).append(" ");
			}
			sb.append("\n");
		}
		System.out.println(sb);
	}
}
반응형