1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| public class Solution {
public void solveSudoku(char[][] board) { boolean[][] r_used = new boolean[9][9]; boolean[][] c_used = new boolean[9][9]; boolean[][][] b_used = new boolean[3][3][9]; List<int[]> ems = new ArrayList<>(); for ( int i = 0; i < 9; i++ ) { for ( int j = 0; j < 9; j++ ) { if ( board[i][j] == '.' ) { int[] empty = {i, j, 0}; ems.add(empty); } else { int num = board[i][j] - 49; myAdjuster( i, j, num, true, r_used, c_used, b_used ); } } } int min_idx = findMin( ems, r_used, c_used, b_used ); mySolver ( board, ems, r_used, c_used, b_used, min_idx); }
private boolean mySolver ( char[][] bd, List<int[]> ems, boolean[][] r_used, boolean[][] c_used, boolean[][][] b_used, int idx ) { if ( idx == -1 ) return true; int[] em = ems.get(idx); ems.remove(em); int i = em[0], j = em[1]; for ( int num = 0; num < 9; num++ ) { if ( !r_used[i][num] && !c_used[j][num] && !b_used[i/3][j/3][num] ) { myAdjuster( i, j, num, true, r_used, c_used, b_used ); int min_idx = findMin( ems, r_used, c_used, b_used ); if ( mySolver ( bd, ems, r_used, c_used, b_used, min_idx) ) { bd[i][j] = (char)(num + 49); return true; } myAdjuster( i, j, num, false, r_used, c_used, b_used ); } } ems.add(em); return false; }
private void myAdjuster( int i, int j, int num, boolean add, boolean[][] r_used, boolean[][] c_used, boolean[][][] b_used ) { if (add) { r_used[i][num] = true; c_used[j][num] = true; b_used[i/3][j/3][num] = true; } else { r_used[i][num] = false; c_used[j][num] = false; b_used[i/3][j/3][num] = false; } }
private int findMin( List<int[]> ems, boolean[][] r_used, boolean[][] c_used, boolean[][][] b_used ) { for ( int[] em : ems ) { int i = em[0], j = em[1]; em[2] = 0; for ( int num = 0; num < 9; num++ ) { if ( !r_used[i][num] && !c_used[j][num] && !b_used[i/3][j/3][num] ) em[2]++; } } int min = 1000, idx = -1; for ( int i = 0; i < ems.size(); i++ ) { int[] em = ems.get(i); if ( em[2] < min ) { min = em[2]; idx = i; } } return idx; } }
|