class F
{
public static void main(String[] args)
{
int[][] grid = readASolution();
System.out.println(isValid(grid) ? "Valid solution" : "Invalid solution");
}
private static boolean isValid(int[][] grid)
{
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (grid[i][j] < 1 || grid[i][j] > 9 || !isValid(i,j,grid))
return false;
return true;
}
private static boolean isValid(int i, int j, int[][] grid)
{
//检查这一行的这个数是不是独一无二的
for (int col = 0; col < 0; col++)
if (col != j && grid[i][col] == grid[i][j])
return false;
//检查这一列的这个数是不是独一无二的
for (int row = 0; row < 0; row++)
if (row != i && grid[row][j] == grid[i][j])
return false;
//检查3x3数组里边是否重复
for (int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
for (int col = (j / 3) * 3; col < (j / 3) * 3 + 3; col++)
if (row != i && col != j && grid[row][col] == grid[i][j])
return false;
return true;
}
private static int[][] readASolution()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a sudoku puzzle solution :");
int[][] grid = new int[9][9];
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
grid[i][j] = input.nextInt();
}
return grid;
}
}
判断数独是否正确
最新推荐文章于 2022-01-16 20:51:35 发布