我想检查整个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];
             for ( int m=0; m<nums.length; m++)
             if ( nums[m]==temp ) return false;
             nums[x++]=temp; }
             return true; }

最佳答案

您可以修改您的checkSubsMethod。


将数独子块左上角的i和j相加(例如(0,0),(0,3),...(3,0),(3,3)...(6,3),( 6,6))。
使用设置来检查是否已使用该值。如果值不在集合中,则Set类的add()方法返回true,如果值已经添加到集合中,则返回false


当您对方法进行概括时,可以将其用于任何大小的字段。在您的情况下,尺寸为9x9,下面是示例

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!!");

}


在这种情况下的输出将是OK!!

如果您这样更改输入

 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}};


输出将是DUPLICATED VALUES FOUND!

您可以根据需要修改此示例。

10-05 18:13