数独优化

lzhphantom 发布于 2017/10/23 16:38

package idea;

import java.util.ArrayList;

public class Sodukus2 {
private int[] special = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private ArrayList<Integer> listTest = new ArrayList<Integer>();
//检查列是否有重复元素
private boolean isExistList(int number, int[][] arr, int list) {
ArrayList<Integer> listarr = new ArrayList<Integer>();
for (int j = 0; j < arr[list].length; j++) {
if (arr[j][list] == number) {
}
}
if (listarr.size() > 1) {
return true;
}

return false;
}

private void getArrayList() {
listTest.clear();
for (int i = 0; i < special.length; i++) {
}

}
//检查9格是否有重复
private boolean isExistNine(int number, int row, int col, int[][] arr) {
ArrayList<Integer> listarr = new ArrayList<Integer>();
int NineRow = row / 3 * 3;
int NineCol = col / 3 * 3;

for (int i = NineRow; i <= NineRow + 2; i++) {
for (int m = NineCol; m <= NineCol + 2; m++) {
if (arr[i][m] == number) {
}
}
}
if (listarr.size() > 1) {
return true;
}

return false;
}

public int[][] getNumber(int[][] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
getArrayList();//重新获取一组元素

for (int j = 0; j < arr[i].length; j++) {
int index = (int) (Math.random() * listTest.size());
arr[i][j] = (Integer) listTest.get(index);//随机获取

if (i > 0) {
while (isExistList(arr[i][j], arr, j)
|| isExistNine(arr[i][j], i, j, arr)) {
count++;//排斥最后一个值与其他无限重复
if (count > 8) {
count = 0;
j = 0;
getArrayList();
}
index = (int) (Math.random() * listTest.size());
arr[i][j] = (Integer) listTest.get(index);
}

}

listTest.remove(index);//删除该元素
}
}
//问题所在：加上这个换行，结果会很快出来，没有加，就不会出来，请大神解答
System.out.println();
return arr;
}

public void print(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}

public static void main(String[] args) {
Sodukus2 sd = new Sodukus2();
int[][] arr = new int[9][9];
arr = sd.getNumber(arr);
sd.print(arr);
}
}

0

0

引用来自“flyingsam”的评论

0
``````                        if (count > 8) {
count = 0;
j = 0;
getArrayList();
}``````

for (int k = 0; k < arr[i].length; k++) {
arr[i][k] = 0;
}