[leedcode 36] Valid Sudoku

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.

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        //本题思路:先每行每列判断是否有重复的数,此题借助arraylist,注意clear,contains,add等方法,当board中的元素不为‘.’时,才进行判断
        //判断完行和列,判断每个3*3的块。注意遍历的方式,四个for循环
        int len=board.length;
        List<Character> row=new ArrayList<Character>();
        List<Character> col=new ArrayList<Character>();
        for(int i=0;i<len;i++){
                row.clear();
                col.clear();
            for(int j=0;j<len;j++){
                
                char r=board[i][j];
                if(r!='.'){
                    if(row.contains(r))
                           return false;
                    else{
                        row.add(r);
                    }
                }
                char c=board[j][i];
                 if(c!='.'){
                    if(col.contains(c))
                           return false;
                    else{
                        col.add(c);
                    }
                }
    
            }
        }
        ArrayList<Character> block=new ArrayList<Character>();
        for(int k=0;k<len;k=k+3){//k代表块的行,s代表块的列。每个块再进行遍历
            for(int s=0;s<len;s=s+3){
                block.clear();
                for(int i=0;i<3;i++){
                    for(int j=0;j<3;j++){
                      char b=board[i+k][j+s];
                        if(b!='.'){
                            if(block.contains(b))
                               return false;
                            else{
                                block.add(b);
                            }
                        }  
                    }
                }
            }
        }
        
        
      return true;  
        
    }
}

 

posted @ 2015-07-09 22:52  ~每天进步一点点~  阅读(115)  评论(0编辑  收藏  举报