gpt4 book ai didi

Java 数独解决方案 validator

转载 作者:行者123 更新时间:2023-12-01 10:47:48 25 4
gpt4 key购买 nike

我目前正在尝试创建一个 Java 程序,将 81 个整数 (1-9) 读取到 9 X 9 矩阵中,然后测试该矩阵是否是数独谜题的解决方案。数独解决方案的参数如下:每个数字 (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.");
}
}

最佳答案

这可能可以优化,但遵循您的方法

// row checker
for(int row = 0; row < 9; row++)
for(int col = 0; col < 8; col++)
for(int col2 = col + 1; col2 < 9; col2++)
if(s[row][col]==s[row][col2])
return false;

// column checker
for(int col = 0; col < 9; col++)
for(int row = 0; row < 8; row++)
for(int row2 = row + 1; row2 < 9; row2++)
if(s[row][col]==s[row2][col])
return false;

// grid checker
for(int row = 0; row < 9; row += 3)
for(int col = 0; col < 9; col += 3)
// row, col is start of the 3 by 3 grid
for(int pos = 0; pos < 8; pos++)
for(int pos2 = pos + 1; pos2 < 9; pos2++)
if(s[row + pos%3][col + pos/3]==s[row + pos2%3][col + pos2/3])
return false;

关于Java 数独解决方案 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34076389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com