Share my C++ solution, 15ms


  • -1
    E
    #define C2B(x) (x>=6 ? 2 : x>=3 ? 1 : 0)
    #define R2B(x) (x>=6 ? 6 : x>=3 ? 3 : 0)
    
    class Solution {
    public:
    	bool isValidSudoku(vector<vector<char> > &board) {
    		int row = board.size();
    		int col = board.size();
    		if (row != 9 || col != 9) {
    			return false;
    		}
    		int bloE[9][10] = { { 0 } };
    		int colE[9][10] = { { 0 } };
    		int rowE[9][10] = { { 0 } };
    		int i = 0;
    		int j = 0;
    		char temp = 0;
    		int ele = 0;
    		int block = 0;
    		for (i = 0; i < row; ++i){
    			for (j = 0; j < col; ++j){
    				temp = board[i][j];
    				if (temp == '.'){
    					continue;
    				}
    				ele = temp - '0';
    				if (1 == colE[j][ele]){		// column conflicted
    					return false;
    				}
    				else {
    					colE[j][ele] = 1;
    				}
    
    				if (1 == rowE[i][ele]) {	// row conficted
    					return false;
    				}
    				else{
    					rowE[i][ele] = 1;
    				}
    				block = R2B(i) + C2B(j);
    				if (1 == bloE[block][ele]){  //block conflicted
    					return false;
    				}
    				else {
    					bloE[block][ele] = 1;
    				}
    			}
    		}
    		return true;
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.