您的位置:首页 > 其它

LeetCode 036 Valid Sudoku

2015-11-10 09:35 357 查看

题目描述

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 ‘.’.



Note:

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

代码

[code]    public static 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;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: