[LeetCode36]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.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Analysis:

first scan every row and column. then scan every square.

Java

public boolean isValidSudoku(char[][] board) {
        ArrayList<Character> row = new ArrayList<>();
        ArrayList<Character> col = new ArrayList<>();
        for(int i=0;i<9;i++){
        	row.clear();
        	col.clear();
        	for(int j=0;j<9;j++){
        		if(board[i][j]!='.'){
        			if(col.contains(board[i][j]))
        				return false;
        			else 
						col.add(board[i][j]);
        		}
        		if(board[j][i]!='.'){
        			if(row.contains(board[j][i]))
        				return false;
        			else
        				row.add(board[j][i]);
        		}
        	}
        }
        ArrayList<Character> block = new ArrayList<>();
        for(int i=0;i<9;i=i+3){
        	for(int j=0;j<9;j=j+3){
        		block.clear();
        		for(int m=0;m<3;m++){
        			for(int n = 0;n<3;n++){
        				if(board[i+m][j+n]!='.')
        					if(block.contains(board[i+m][j+n])) return false;
        					else block.add(board[i+m][j+n]);
        			}
        		}
        	}
        }
        return true;
    }
c++

bool isValidSudoku(vector<vector<char> > &board) {
        for(int i=0; i<board.size(); i++){
        for(int j=0; j<board[i].size();j++){
            for(int k=j+1; k<board[i].size();k++){
                if(board[i][j] == board[i][k] && board[i][j]!='.')
                    return false;
            }
            for(int k=0; k<board.size(); k++){
                if(board[i][j] == board[k][j] && board[i][j]!='.' && i!=k)
                    return false;
            }
        }
    }
    int row[9];
    for(int i=0; i<9;i+=3){
        for(int j=0; j<9; j+=3){
            memset(row,0,9*sizeof(int));
            for(int m=0; m<3;m++){
                for(int n=0; n<3;n++){
                    if(board[i+m][j+n] == '.')
                        continue;
                    if(row[board[m+i][j+n]-49] == 1)
                        return false;
                    row[board[m+i][j+n]-49]++;
                }
            }
        }
    }
    return true;
    }




你可能感兴趣的:(LeetCode,array,数独)