|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | + |
| 6 | +class Main { |
| 7 | + private static int[] horizontalBit = new int[9]; |
| 8 | + private static int[] verticalBit = new int[9]; |
| 9 | + private static int[] sectionBit = new int[9]; |
| 10 | + |
| 11 | + private static int[][] map = new int[9][9]; |
| 12 | + |
| 13 | + private static int[] emptyRows = new int[81]; |
| 14 | + private static int[] emptyCols = new int[81]; |
| 15 | + private static int emptyCount = 0; |
| 16 | + |
| 17 | + private static StringBuilder result = new StringBuilder(); |
| 18 | + |
| 19 | + public static void main(String[] args) throws IOException { |
| 20 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 21 | + |
| 22 | + for (int i = 0; i < 9; i++) { |
| 23 | + String line = br.readLine(); |
| 24 | + for (int j = 0; j < 9; j++) { |
| 25 | + int num = line.charAt(j) - '0'; |
| 26 | + map[i][j] = num; |
| 27 | + |
| 28 | + if (num == 0) { |
| 29 | + emptyRows[emptyCount] = i; |
| 30 | + emptyCols[emptyCount] = j; |
| 31 | + emptyCount++; |
| 32 | + continue; |
| 33 | + } |
| 34 | + |
| 35 | + int bitMask = 1 << (num - 1); |
| 36 | + horizontalBit[i] |= bitMask; |
| 37 | + verticalBit[j] |= bitMask; |
| 38 | + sectionBit[getSectionNumber(i, j)] |= bitMask; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + solve(0); |
| 43 | + |
| 44 | + for (int i = 0; i < 9; i++) { |
| 45 | + for (int j = 0; j < 9; j++) { |
| 46 | + result.append(map[i][j]); |
| 47 | + } |
| 48 | + result.append('\n'); |
| 49 | + } |
| 50 | + System.out.print(result); |
| 51 | + } |
| 52 | + |
| 53 | + private static boolean solve(int index) { |
| 54 | + if (index == emptyCount) { |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + int row = emptyRows[index]; |
| 59 | + int col = emptyCols[index]; |
| 60 | + int sectionNum = getSectionNumber(row, col); |
| 61 | + |
| 62 | + int usedBits = horizontalBit[row] | verticalBit[col] | sectionBit[sectionNum]; |
| 63 | + |
| 64 | + for (int num = 1; num <= 9; num++) { |
| 65 | + int bitMask = 1 << (num - 1); |
| 66 | + |
| 67 | + if ((usedBits & bitMask) == 0) { |
| 68 | + map[row][col] = num; |
| 69 | + horizontalBit[row] |= bitMask; |
| 70 | + verticalBit[col] |= bitMask; |
| 71 | + sectionBit[sectionNum] |= bitMask; |
| 72 | + |
| 73 | + if (solve(index + 1)) { |
| 74 | + return true; |
| 75 | + } |
| 76 | + |
| 77 | + map[row][col] = 0; |
| 78 | + horizontalBit[row] &= ~bitMask; |
| 79 | + verticalBit[col] &= ~bitMask; |
| 80 | + sectionBit[sectionNum] &= ~bitMask; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + private static int getSectionNumber(int row, int col) { |
| 88 | + return (row / 3) * 3 + (col / 3); |
| 89 | + } |
| 90 | +} |
| 91 | +``` |
0 commit comments