Start
public class SudokuGame { public static void main(String[] args) { SudokuGenerator generator = new SudokuGenerator(); int[][] borad = generator.generate(); Sudoku sudoku = new Sudoku(borad); sudoku.printf(); } }
public class Sudoku { private int[][] board; public Sudoku(int[][] board) { this.board = board; } public void printf() { StringBuffer outStr = new StringBuffer(); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { //System.out.println(board[i][j] + " "); outStr.append(board[i][j]).append(" "); } System.out.println(outStr.toString()); outStr.delete(0, outStr.length()); //System.out.println(""); } } }
import java.util.Random; public class SudokuGenerator { private static final int BOARD_SIZE = 9; private static final int SUBGRID_SIZE = 3; private int[][] board; public SudokuGenerator() { // 棋盘大小9*9 board = new int[BOARD_SIZE][BOARD_SIZE]; } public int[][] generate() { fillValues(); return board; } private void fillValues() { fillDiagonalSubgrids(); fillRemaining(0, SUBGRID_SIZE); } private void fillDiagonalSubgrids() { for (int i = 0; i < BOARD_SIZE; i += SUBGRID_SIZE) { fillSubgrid(i, i); } } private boolean fillRemaining(int row, int col) { if (row == BOARD_SIZE - 1 && col == BOARD_SIZE) { return true; } if (col == BOARD_SIZE) { row++; col = 0; } if (board[row][col] != 0) { return fillRemaining(row, col + 1); } for (int num = 1; num <= BOARD_SIZE; num++) { if (isSafeToPlaceNum(row, col, num)) { board[row][col] = num; if (fillRemaining(row, col + 1)) { return true; } } } board[row][col] = 0; return false; } private void fillSubgrid(int row, int col) { int num; for (int i = 0; i < SUBGRID_SIZE; i++) { for (int j = 0; j < SUBGRID_SIZE; j++) { do { num = getRandomNumber(); } while (!isSafeToPlaceNum(row + i, col + j, num)); board[row + i][col + j] = num; } } } private boolean isSafeToPlaceNum(int row, int col, int num) { return !isInRow(row, num) && !isInCol(col, num) && !isInSubgrid(row - row % SUBGRID_SIZE, col - col % SUBGRID_SIZE, num); } private boolean isInRow(int row, int num) { for (int i = 0; i < BOARD_SIZE; i++) { if (board[row][i] == num) { return true; } } return false; } private boolean isInCol(int col, int num) { for (int i = 0; i < BOARD_SIZE; i++) { if (board[i][col] == num) { return true; } } return false; } private boolean isInSubgrid(int row, int col, int num) { for (int i = 0; i < SUBGRID_SIZE; i++) { for (int j = 0; j < SUBGRID_SIZE; j++) { if (board[row + i][col + j] == num) { return true; } } } return false; } private int getRandomNumber() { return new Random().nextInt(BOARD_SIZE) + 1; } }
End
标签:BOARD,JAVA,游戏,int,private,board,public,数独,SIZE From: https://www.cnblogs.com/lnsylt/p/17749568.html