我目前正在尝试创建一个Java程序,将81个整数(1-9)读入9×9矩阵,然后测试该矩阵是否是Sudoku难题的解决方案。 Sudoku解决方案的参数如下:每个数字(1-9)必须在每个行,列和3x3方格中表示,而不会在这些区域中重复。我已经编写了一个方法来验证所有行和列是否满足参数,但是,我正在努力想出一个算法来验证方块。以下是我到目前为止的情况:
import java.util.*;
public class SudokuCheck
{
public static boolean sudokuCheck(int[][] s)
{
for(int row=0;row<9;row++)
for(int col=0;col<8;col++)
if(s[row][col]==s[row][col+1]){
return false;}
//Verifies rows
for(int col2=0;col2<9;col2++)
for(int row2=0;row2<8;row2++)
if (s[row2][col2]==s[row2+1][col2])
return false;
//verifies columns
return true;
}
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
int[][] solution = new int [9][9];
System.out.println("Enter the values of a 9 X 9 Sudoku solution");
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
solution[i][j]=input.nextInt();
//read values into matrix
if(sudokuCheck(solution)==true)
System.out.println("The entered 9 X 9 grid is a solution to a Sudoku puzzle.");
else
System.out.println("The entered 9 X 9 grid is not a solution to a Sudoku puzzle.");
}
}
答案 0 :(得分:2)
这可以根据您的方法进行优化
myDate.ToString("yyyy-MM-dd HH':'mm':'ss")
答案 1 :(得分:0)
我希望它可以帮到你
public static void main(String[] args) throws Exception {
int[][] f = {{4,2,9,8,1,3,5,6,7}, {5,1,6,4,7,2,9,3,8}, {7,8,3,6,5,9,2,4,1},
{6,7,2,1,3,4,8,5,9}, {3,9,5,2,8,6,1,7,4}, {8,4,1,7,9,5,6,2,3},
{1,5,8,3,6,7,4,9,2}, {9,3,4,5,2,8,7,1,6}, {2,6,7,9,4,1,3,8,5}};
System.out.println(Arrays.toString(f));
System.out.println(checkBlock(f, 2, 2));
}
public static boolean checkBlock(int[][] f, int z, int s) throws Exception {
boolean[] mark = new boolean[9];
boolean res = true;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int v = f[z * 3 + i][s * 3 + j];
if (v == 0) {
res = false;
}
if (mark[v - 1]) {
throw new Exception();
}
mark[v - 1] = true;
}
}
return res;
}
答案 2 :(得分:-1)
docker-compose.yml