Java Sudoku解决方案验证程序

编程入门 行业动态 更新时间:2024-10-07 14:29:53
本文介绍了Java Sudoku解决方案验证程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在尝试创建一个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解决方案验证程序

本文发布于:2023-11-01 01:01:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1547788.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解决方案   程序   Java   Sudoku

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!