合法的数独

什么数独题目是合理的呢?

每一行都不能有重复数字,而且属于[0,9]

每一列都不能有重复数字,而且属于[0,9]

3*3分割整张表,每个小表内数字都要属于[0,9]

shudu

 

/**
 * Created by chris on 2014/11/24.
 */
public class ValidSudoku {
    public final int square = 3;
    public final int squ2 = 9;
    public boolean isValidSudoku(char[][] board) {
        boolean col = isValidColom(board);
        boolean row  = isValidRow(board);
        boolean squ = isValidSqu(board);

        return col && row && squ;
    }
    //按照每3*3个格子的方块检查,是否有重复数
    private boolean isValidSqu(char[][] board) {
        int a[] = new int[10];

        for (int i = 0; i < board.length; ) {
            for (int j = 0; j < board[0].length; ) {
                for (int k = i; k < i + square; k++) {
                    for (int l = j; l < j + square; l++) {
                        if (board[k][l] >= '0' && board[k][l] <= '9') {
                            int m = board[k][l] - '0';
                            a[m]++;
                        }
                    }//end of for l
                }// end of for k

                for (int k = 0; k <= squ2; k++) {
                    if (a[k] > 1) return false;
                    else a[k] = 0;
                }
            j += 3;
            }//end of j

            i+=3;
        }//end of i
        return true;
    }

    //按照每行9个格子检查,是否有重复数
    private boolean isValidRow(char[][] board) {
        int rowLenth = board.length;

        int a[] = new int[10];
        for (int i = 0; i < rowLenth; i++) {

            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] >= '0' && board[i][j] <= '9'){
                     int k = board[i][j] - '0';
                    a[k]++;
                }
            }

            for (int j = 0; j < a.length; j++) {
                if (a[j] > 1) return false;
                else a[j] = 0;
            }
        }
        return true;
    }

    //按照每列9个格子检查,是否有重复数

    private boolean isValidColom(char[][] board) {
        int colenth = board[0].length;
        int a[] = new int[10];
        for (int i = 0; i < colenth; i++) {
            for (int j = 0; j < board.length; j++) {
                if (board[j][i] >= '0' && board[j][i] <= '9'){
                    int k = board[j][i] - '0';
                    a[k]++;
                }
            }
            for (int j = 0; j < a.length; j++) {
                if (a[j] > 1) return false;
                else a[j] = 0;
            }
        }
        return true;
    }
}
Tagged on: , ,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>