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 Sudo { static char[] numbers = {'1','2','3','4','5','6','7','8','9'};
public static void main(String[] args) { char[][] board = {{'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'}}; writeInto(board); for(int i = 0; i < 9; i++) { for(int j = 0; j <9; j++){ System.out.print(board[i][j]); if(j==8){ System.out.println(); } } }
}
public static void writeInto(char[][] board){ int[] index = findBlank(board); if(index[0] == 10){ return; } for(char number : numbers){ if(checkSelf(index[0],index[1],number,board) && checkClo(number,board,index[1]) && checkRow(number,board[index[0]])){ board[index[0]][index[1]] = number; writeInto(board); int[] index1 = findBlank(board); if(index1[0] == 10){ return; } board[index[0]][index[1]] = '.'; } } }
public static int[] findBlank(char[][] board){ int[] index = {10,10}; for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ if(board[i][j] == '.'){ index[0] = i; index[1] = j; return index; } } } return index; }
public static boolean checkRow(char number, char[] row){ for(char n : row){ if(n == number){ return false; } } return true; }
public static boolean checkClo(char number, char[][] board, int clo){ for(int i = 0; i < 9; i++){ if(board[i][clo] == number){ return false; } } return true; }
public static boolean checkSelf(int x, int y, char number, char[][] board){ int x_range = (x / 3) * 3; int y_range = (y / 3) * 3; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ if(number == board[x_range + i][y_range + j]){ return false; } } } return true; } }
|