java课程 数独 文库_数独 (java)

package qunxingw.com;

import java.util.Scanner;

public class Soudu {

static int[][] array = new int[9][9];

public void show(int array[][]) {

for (int i = 0; i < 9; i++) {

for (int j = 0; j < 9; j++) {

System.out.print(array[i][j] + " ");

}

System.out.println("\n");

}

System.out.println("**************************************");

}

public void setarray(int array[][], int i, int j, int k) {

array[i][j] = k;

}

public boolean check(int array[][], int r, int c, int k) {

int i, j;

// 该单元格的所在行的其他单元格是否已选K

for (i = 0; i < 9; i++) {

if (array[i][c] == k) {

return false;

}

}

// 该单元格的所在列的其他单元格是否已选K

for (j = 0; j < 9; j++) {

if (array[r][j] == k) {

return false;

}

}

// 该单元格小九宫内是否可选k

int temp1, temp2;

temp1 = r / 3 * 3;

temp2 = c / 3 * 3;

for (i = temp1; i < temp1 + 3; i++) {

for (j = temp2; j < temp2 + 3; j++) {

if (array[i][j] == k) {

return false;

}

}

}

return true;

}

public void soudugame(int array[][], int num) {

int i, j;

int[][] temp = new int[9][9];

for (i = 0; i < 9; i++)

for (j = 0; j < 9; j++) {

temp[i][j] = array[i][j];

}

i = num / 9;

j = num % 9;

// 此格有数时

if (temp[i][j] != 0) {

if (num == 80) {

// count++;

show(temp);

} else {

soudugame(temp, num + 1);

}

}

// 0时选个不冲突的数

else {

for (int k = 1; k <= 9; k++) {

if (check(temp, i, j, k)) {

temp[i][j] = k;

if (num == 80) {

// count++;

show(temp);

} else {

soudugame(temp, num + 1);

}

}

temp[i][j] = 0;

}

}

}

public static void main(String[] args) {

int i, j, k, n;

Soudu soudu = new Soudu();

Scanner scan = new Scanner(System.in);

System.out.println("原始数独有几个数?");

n = scan.nextInt();

System.out.println("第一个数:行,第二个为:列;第三个数为 数独数");

while (n > 0) {

n--;

i = scan.nextInt() - 1;// 行号从1--9

j = scan.nextInt() - 1;// 列号 1--9

k = scan.nextInt();// 此格中初始固定值

soudu.setarray(array, i, j, k);

}

soudu.show(array);

soudu.soudugame(array, 0);

}

}

基本设计思想与8皇后差不多,注意2个细节

1,遍历时分数组中是否有原始数

2,在没有原始数时找k值时要用temp数组处理,主要是让temp[i][j]取不同的K值,以便递归。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值