当前位置:网站首页>Leetcode topic resolution valid Sudoku

Leetcode topic resolution valid Sudoku

2022-06-23 06:17:00 ruochen

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

A partially filled sudoku which is valid.

Note:

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Check rows separately 、 Column 、3*3 square .

    public boolean isValidSudoku(char[][] board) {
        if (board == null || board.length != 9 || board[0].length != 9) {
            return false;
        }
        int mx = board.length;
        int my = board[0].length;
        // row
        for (int x = 0; x < mx; x++) {
            boolean[] flag = new boolean[10];
            for (int y = 0; y < my; y++) {
                char c = board[x][y];
                if (c != '.') {
                    if (flag[c - '0'] == false) {
                        flag[c - '0'] = true;
                    } else {
                        return false;
                    }
                }
            }
        }
        // column
        for (int y = 0; y < my; y++) {
            boolean[] flag = new boolean[10];
            for (int x = 0; x < mx; x++) {
                char c = board[x][y];
                if (c != '.') {
                    if (flag[c - '0'] == false) {
                        flag[c - '0'] = true;
                    } else {
                        return false;
                    }
                }
            }
        }
        // square
        for (int x = 0; x < mx / 3; x++) {
            for (int y = 0; y < my / 3; y++) {
                boolean[] flag = new boolean[10];
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        char c = board[x * 3 + i][y * 3 + j];
                        if (c != '.') {
                            if (flag[c - '0'] == false) {
                                flag[c - '0'] = true;
                            } else {
                                return false;
                            }
                        }
                    }
                }
            }
        }
        return true;
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201141141224549.html