Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何确保每个3x3块都包含数独中的值_Java_Arrays_Nested_Sudoku - Fatal编程技术网

Java 如何确保每个3x3块都包含数独中的值

Java 如何确保每个3x3块都包含数独中的值,java,arrays,nested,sudoku,Java,Arrays,Nested,Sudoku,我想检查整个数独表是否所有的块都得到了9个值,但我只能检查第一个块,我需要检查其他8个块如何 public static boolean checkSubs(int[][] p) { int[] nums = new int[9]; int x=0, temp; for (int i=0; i<3; i++) for (int j=0; j<3; j++) { temp = p[i][j];

我想检查整个数独表是否所有的块都得到了9个值,但我只能检查第一个块,我需要检查其他8个块如何

 public static boolean checkSubs(int[][] p) {
       int[] nums = new int[9];
       int x=0, temp;
        for (int i=0; i<3; i++)
           for (int j=0; j<3; j++) {
             temp = p[i][j];
             for ( int m=0; m<nums.length; m++)
             if ( nums[m]==temp ) return false; 
             nums[x++]=temp; }
             return true; }
公共静态布尔checkSubs(int[]p){
int[]nums=新的int[9];
INTX=0,温度;

对于(int i=0;i您可以修改您的方法

  • 添加数独子块左上角的i和j(例如(0,0),(0,3),…(3,0),(3,3)…(6,3),(6,6))
  • 使用set检查值是否已使用。set类的add()方法返回
    true
    如果值不在集合中,如果值已添加到集合中,则返回
    false
当你推广你的方法时,你可以将它用于任何大小的字段

public static boolean checkSubs(int[][] p, int topI, int topJ) {
    Set<Integer> nums = new HashSet<>();
    for (int i = topI; i < topI + 3; i++) {
        for (int j = topJ; j < topJ + 3; j++) {
            if (!nums.add(p[i][j])) {
                return false;
            }
        }
    }
    return true;
}

public static void main(String[] args) {
    int[][] sudoku = {
        {1,2,3,1,2,3,1,2,3},
        {4,5,6,4,5,6,4,5,6},
        {7,8,9,7,8,9,7,8,9},
        {1,2,3,1,2,3,1,2,3},
        {4,5,6,4,5,6,4,5,6},
        {7,8,9,7,8,9,7,8,9},
        {1,2,3,1,2,3,1,2,3},
        {4,5,6,4,5,6,4,5,6},
        {7,8,9,7,8,9,7,8,9}};

    for (int i = 0; i < sudoku.length;i += 3){
        for (int j = 0; j<sudoku[0].length; j += 3){
            if (!checkSubs(sudoku, i, j)){
                System.out.println("DUPLICATED VALUES FOUND!");
                return;
            }
        }
    }
    System.out.println("OK!!");

}
输出将是
找到的重复值!


您可以修改此示例以供将来使用。

对3到6和6到9执行相同的操作。并修复缩进。不会仍然检查所有块
 int[][] sudoku = {
 {3,3,3,1,2,3,1,2,3},
 {4,5,6,4,5,6,4,5,6},
 {7,8,9,7,8,9,7,8,9},
 {1,2,3,1,2,3,1,2,3},
 {4,5,6,4,5,6,4,5,6},
 {7,8,9,7,8,9,7,8,9},
 {1,2,3,1,2,3,1,2,3},
 {4,5,6,4,5,6,4,5,6},
 {7,8,9,7,8,9,7,8,9}};