LeetCode -- Valid Sudoku

Question:

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.

 

Anslysis:

问题描述:判断一个数独游戏是否合法。数独当前可以是部分填充,未填充部分用'.'代替。有效地数独并不是指该游戏是否有解,而仅仅判断当前填充是否有效。

数独有效是指:每一行,每一列,以及每个小得九宫格的当前填充是否有重复数字。

思路:看到题目,分析完成后的直接思路是,分别判断数独的每一行,每一列,每九宫格是否含有相同的数字,如果含有就不是有效地数独。

Answer:

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        //横向判断
        for(int i=0; i<board.length; i++) {
            HashSet<Character> v = new HashSet<Character>();
            for(int j=0; j<board[i].length; j++) {
                if(board[i][j] != '.') {
                    if(!v.contains(board[i][j]))
                        v.add(board[i][j]);
                    else
                        return false;
                }
            }
        }
        
        //纵向判断
        for(int i=0; i<board[0].length; i++) {
            HashSet<Character> v = new HashSet<Character>();
            for(int j=0; j<board.length; j++) {
                if(board[j][i] != '.') {
                    if(!v.contains(board[j][i]))
                        v.add(board[j][i]);
                    else
                        return false;
                }
            }
        }
        
        //九宫格判断
        int i = 0, j = 0;
        while(i < board.length) {
            j = 0;
            while(j < board[0].length) {
                HashSet<Character> v = new HashSet<Character>();
                for(int t=0; t<3; t++) {
                    for(int k=0; k<3; k++) {
                        if(board[i+t][j+k] != '.') {
                            if(!v.contains(board[i+t][j+k]))
                                v.add(board[i+t][j+k]);
                            else
                                return false;
                        }
                    }
                }
                j = j + 3;
            }
            i = i + 3;
        }
        return true;
            
    }
}

 

posted @ 2015-10-05 16:42  江湖小妞  阅读(288)  评论(0编辑  收藏  举报