class="java" name="code"> import java.util.Random; public class Shudu { private int[][] pan = new int[9][9]; private final static int EASY = 20; private final static int NORMAL = 40; private final static int HARD = 60; public static void main(String[] args) { Shudu s = new Shudu(); s.init(); s.fillTheFirstRow(); s.fillOtherCellAndCheck(); s.sudoku(NORMAL); s.out(); } //初始化各个值为0 public void init() { for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { pan[i][j] = 0; } } } //设置第一行的值,随机1-9 public void fillTheFirstRow() { pan[0][random()] = 1; for(int cellValue = 2; cellValue < 10; cellValue++){ int col = random(); while(pan[0][col] != 0){ col = random(); } pan[0][col] = cellValue; } } public void fillOtherCellAndCheck() { int row = 1, col = 0; do { pan[row][col]++; //如果为10的话表示失败,回退继续判断 if(pan[row][col] == 10) { pan[row][col] = 0; col--; if(col < 0) { row--; col = 8; } continue; } //判断行中的数是否为1-9且不重复,成功则前进 if(checkRow(row,col,pan[row][col])) { col++; if(col == 9) { row++; col = 0; } } }while(row < 9); } public int random() { Random random = new Random(); return random.nextInt(9); } public boolean checkRow(int row, int col, int cellValue) { for(int i = 0; i < 9; i++) { if(i == col) { continue; } if(pan[row][i] == cellValue) { return false; } } return checkCol(row, col, cellValue); } public boolean checkCol(int row, int col, int cellValue) { for(int i = 0; i < 9; i++) { if(i == row) { continue; } if(pan[i][col] == cellValue) { return false; } } return checkSudoku(row, col, cellValue); } public boolean checkSudoku(int row, int col, int cellValue) { int n = row / 3; int m = col / 3; for(int i = n*3; i < 3*(n+1); i++){ for(int j = m*3; j < 3*(m+1); j++){ if(row== i && col == j) { continue; } if(pan[i][j] == cellValue) { return false; } } } return true; } //随机设置count个cell的值为0 public void sudoku(int count) { for(int i = 0; i < count; i++) { int row = random(); int col = random(); while(pan[row][col] == 0) { row = random(); col = random(); } pan[row][col] = 0; } } public void out() { for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { System.out.print(pan[i][j] + " "); if((j+1) % 3 == 0 && j != 8) { System.out.print(" "); } if(j == 8) { System.out.println(""); } } if((i+1) % 3 == 0 && i != 8) { System.out.println(""); } } } }