Valid Sudoku, Leetcode 解题笔记

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

250px-Sudoku-by-L2G-20050714.svg
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.

这道题很直接,用hashmap实现。先比行,再比列,最后比九格。

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        for(int i=0; i<board[0].length; i++){  
            HashSet<Character> test = new HashSet<Character>();  
            for(int j=0; j<board.length; j++){  
                if(board[j][i]!='.' && !test.add(board[j][i])) return false;  
            }  
        }  
          
        // rule2, row  
        for(int i=0; i<board.length; i++){  
            HashSet<Character> test = new HashSet<Character>();  
            for(int j=0; j<board[0].length; j++){  
                if(board[i][j]!='.' && !test.add(board[i][j])) return false;  
            }  
        }     
          
        // rule3, sub-box  
        for(int i=0; i<3; i++){  
            for(int j=0; j<3; j++){// for each sub-box  
                HashSet<Character> test = new HashSet<Character>();  
                for(int m=i*3; m<i*3+3; m++){//row  
                    for(int n=j*3; n<j*3+3; n++){//column  
                        if(board[m][n]!='.' && !test.add(board[m][n])) return false;  
                    }  
                }  
            }  
        }  
          
        return true;  
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s