Valid Sudoku

来源:互联网 发布:windows中国官方网 编辑:程序博客网 时间:2024/06/03 15:29

Q:

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.


Solution:

public class Solution {    public boolean isValidSudoku(char[][] board) {        Map<Integer, Integer> row = new HashMap<Integer, Integer>();        Map<Integer, Integer> col = new HashMap<Integer, Integer>();        Map<Integer, Integer> box = new HashMap<Integer, Integer>();        for (int i = 0; i < 9; i++) {            for (int j = 0; j < 9; j++) {                if (board[i][j] != '.' && row.get(board[i][j] - '0') != null)                     return false;                if (board[j][i] != '.' && col.get(board[j][i] - '0') != null)                    return false;                if (board[(i%3)*3 + j/3][j%3 + i/3*3] != '.' && box.get(board[(i%3)*3 + j/3][j%3 + i/3*3] - '0') != null)                    return false;                row.put(board[i][j] - '0', 1);                col.put(board[j][i] - '0', 1);                box.put(board[(i%3)*3 + j/3][j%3 + i/3*3] - '0', 1);            }            row.clear();            col.clear();            box.clear();        }        return true;    }}


0 0
原创粉丝点击