TypechoJoeTheme

IT技术分享

统计

[LeetCode 36] Valid Sudoku [Java]

2018-01-19
/
0 评论
/
702 阅读
/
正在检测是否收录...
01/19

1. Description

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.

2. Code

import java.util.HashSet;
import java.util.Set;

public class LeetCode0036 {

    public boolean isValidSudoku(char[][] board) {
        if (board == null || board.length != 9 || board[0] == null || board[0].length != 9) {
            return false;
        }

        Set[][] block = new HashSet[3][3];

        for (int i = 0; i < 9; i++) {

            Set row = new HashSet();
            Set col = new HashSet();

            for (int j = 0; j < 9; j++) {
                if (board[j][i] != '.' && !col.add(board[j][i])) {
                    return false;
                }

                if (board[i][j] == '.') {
                    continue;
                }

                if (!row.add(board[i][j])) {
                    return false;
                }

                if (block[i / 3][j / 3] == null) {
                    block[i / 3][j / 3] = new HashSet();
                }
                if (!block[i / 3][j / 3].add(board[i][j])) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        LeetCode0036 leetcode = new LeetCode0036();
        System.out.println(leetcode.isValidSudoku(new char[][] { { '.', '8', '7', '6', '5', '4', '3', '2', '1' },
                { '2', '.', '.', '.', '.', '.', '.', '.', '.' }, { '3', '.', '.', '.', '.', '.', '.', '.', '.' },
                { '4', '.', '.', '.', '.', '.', '.', '.', '.' }, { '5', '.', '.', '.', '.', '.', '.', '.', '.' },
                { '6', '.', '.', '.', '.', '.', '.', '.', '.' }, { '7', '.', '.', '.', '.', '.', '.', '.', '.' },
                { '8', '.', '.', '.', '.', '.', '.', '.', '.' }, { '9', '.', '.', '.', '.', '.', '.', '.', '.' } }));
    }
}
Set
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1388/(转载时请注明本文出处及文章链接)