我目前正在尝试创建一个Java程序,该程序将81个整数(1-9)读入9 X 9矩阵,然后进行测试以查看该矩阵是否是Sudoku难题的解决方案. Sudoku解决方案的参数如下:每个数字(1-9)必须在每一行,每一列和3x3正方形中表示,在这些区域中不得重复.我已经编写了一种方法来验证是否所有行和列都满足参数,但是,我正在努力提出一种算法来验证平方.这是我到目前为止的内容:
I am currently attempting to create a Java program that reads 81 integers (1-9) into an 9 X 9 matrix, and then tests to see if that matrix is a solution to a Sudoku puzzle. The parameters for a Sudoku solution are as follows: each number (1-9) must be represented in every row, column, and 3x3 square without any repetition in these areas. I have written a method to verify that the parameters are met for all rows and columns, however, I am struggling with coming up with an algorithm to verify the squares. Here is what I have so far:
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."); } }推荐答案
虽然可以按照您的方法进行优化
This can probably be optimized but following your approach
// 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 Sudoku解决方案验证程序
发布评论