码迷,mamicode.com
首页 > 其他好文 > 详细

36. Valid Sudoku

时间:2018-09-20 18:49:54      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:c++   black   The   length   bsp   span   int   art   using   

https://www.youtube.com/watch?v=iqe1JSjyldo

Your answer
false
Expected answer
true




class Solution {
    public boolean isValidSudoku(char[][] board) {
        
        // check each row using a hashset , check each col using a hashes 
        //Check each 3 * 3 black using hashset 
        // check every row 
        // check every col 
        // check every 3 * 3 block 
        // correct corrdinates 
        
        if(!checkRow(board)) return false;
        if(!checkCol(board)) return false;
        if(!checkBlock(board)) return false;
        return true;
    }    
    private boolean checkRow(char[][] board){
        
        // row is from 0 to board.length, col is from 0 to board[0].length 
        for(int i = 0; i < board.length; i++){
            HashSet<Character> set = new HashSet<>();
            for(int j = 0; j < board[0].length; j++){
                if(!set.add(board[i][j])) return false;
            }
        }
        return true;
    }
    
    private boolean checkCol(char[][] board){
        // reverse order of checkRow 
        for(int i = 0; i < board[0].length; i++){
            HashSet<Character> set = new HashSet<>();
            for(int j = 0; j < board.length; j++){
                if(!set.add(board[i][j])) return false;
            }
        }
        return true;
    }
    
    private boolean checkBlock(char[][] board){
        // get start point for every 3 * 3 block, level by level 
        for(int i = 0; i < 3; i++){
            for(int j = 0; j < 3; j++){
                int row = 3 * i;
                int col = 3 * j;
                HashSet<Character> set = new HashSet<>();
                // now we have the start point coordinates, now we can check every block 
                for(int r = row; r < row + 3; r++){
                    for(int c = col; c < col + 3; c++){
                        if(!set.add(board[r][c])) return false;
                    }
                }
            }
        }
        return true;    
    }
}

 

36. Valid Sudoku

标签:c++   black   The   length   bsp   span   int   art   using   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9682513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!