FTPrep, 36 Valid Sudoku

来源:互联网 发布:android滑动解锁源码 编辑:程序博客网 时间:2024/06/05 11:29

TODO: 直到第三次  one-time bug-free 的记录,copy 过来


代码1:

public class Solution {    public boolean isValidSudoku(char[][] board) {        if(board.length!=9 || board[0].length!=9) return false;        int height=board.length;        int width=board[0].length;        for(int i=0; i<height; ++i){            HashSet<Character> set = new HashSet<>();            for(int j=0; j<width; ++j){                if(board[i][j]=='.') continue;                if(set.add(board[i][j])==false) return false;            }        }        for(int i=0; i<width; ++i){            HashSet<Character> set= new HashSet<>();            for(int j=0; j<height; ++j){                if(board[j][i]=='.') continue;                if(set.add(board[j][i])==false) return false;            }        }                for(int i=0; i<width; i+=3){            for(int j=0; j<height; j+=3){                HashSet<Character> set = new HashSet<>();                for(int x=i; x<i+3; ++x){                    for(int y=j; y<j+3; ++y){                        if(board[y][x]=='.') continue;                        if(set.add(board[y][x])==false) return false;                    }                }            }        }        return true;    }} 

代码2:

public class Solution {    public boolean isValidSudoku(char[][] board) {        if(board.length!=9 || board[0].length!=9) return false;        int height=board.length, width=board[0].length;        for(int i=0; i<height; i++){            HashSet<Character> set = new HashSet<>();            for(int j=0; j<width; j++){                if(!checking(board, i, j, set)) return false;            }        }                for(int i=0; i<width; i++){            HashSet<Character> set = new HashSet<>();            for(int j=0; j<height; j++){                if(!checking(board, j, i, set)) return false;            }        }                for(int i=0; i<width; i+=3){            for(int j=0; j<height; j+=3){                HashSet<Character> set = new HashSet<>();                for(int x=i; x<i+3; x++){                    for(int y=j; y<j+3; y++){                        if(!checking(board, y, x, set)) return false;                    }                }            }        }        return true;    }        private boolean checking(char[][] board, int i, int j, HashSet<Character> set){        if(board[i][j]=='.') return true;        else return set.add(board[i][j]);    }}


原创粉丝点击