[leetcode] 36. 有效的数独(Java)

没啥好说的,直接上就行

36. 有效的数独


class Solution {
public boolean isValidSudoku(char[][] board) {

        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < 9; i++) {
            map.clear();
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    if (map.containsKey(board[i][j])) {
                        return false;
                    }
                    map.put(board[i][j], 1);
                }
            }
        }

        for (int j = 0; j < 9; j++) {
            map.clear();
            for (int i = 0; i < 9; i++) {
                if (board[i][j] != '.') {
                    if (map.containsKey(board[i][j])) {
                        return false;
                    }
                    map.put(board[i][j], 1);
                }
            }
        }

        int[][] flag = {{0, 0}, {0, 3}, {0, 6},
                {3, 0}, {3, 3}, {3, 6},
                {6, 0}, {6, 3}, {6, 6},};

        for (int k = 0; k < 9; k++) {
            map.clear();
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    int p = i + flag[k][0];
                    int q = j + flag[k][1];
                    if (board[p][q] != '.') {
                        if (map.containsKey(board[p][q])) {
                            return false;
                        }

                        map.put(board[p][q], 1);
                    }
                }
            }
        }

        return true;
    }
}
posted @ 2018-07-13 00:34  ACBingo  阅读(709)  评论(0编辑  收藏  举报