如何确保每个3x3块包含Sudoku中的值

时间:2018-05-09 17:41:44

标签: 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];
             for ( int m=0; m<nums.length; m++)
             if ( nums[m]==temp ) return false; 
             nums[x++]=temp; }
             return true; }

1 个答案:

答案 0 :(得分:1)

您可以修改checkSubsMethod。

  • 添加数独子块左上角的i和j(例如(0,0),(0,3),...(3,0),(3,3)......(6,3) ),(6,6))。
  • 使用set来检查已使用的值是否已经使用。如果值不在集合中,则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!

您可以在将来修改此示例。