自己写的一个数独生成程序


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("");
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值