首页 > 代码库 > 【leetcode】Valid Sudoku

【leetcode】Valid Sudoku

问题:

Sudoku Solver 中说道,会有一些提示解,这里就是验证下给定的提示解是否合法,即已经填加的数是否满足要求的三个条件。

bool isValidSudoku(vector<vector<char> > &board) {
	
    const int M = 9;//9 * 9
	const int hash_len = 60;//'0' = 48 + 10
	const char dot = '.';
	//check rows 
	for(int i = 0; i < M; ++i)
	{
	  bool rows[hash_len] = {false};
	  bool cols[hash_len] = {false};
	  for(int j = 0; j < M; ++j){
	    if(board[i][j] != dot)
	    {
	        if(rows[board[i][j]])
	            return false;
	        else 
	            rows[board[i][j]] = true;
	    }
	    
	  }
	}
   //check cols
    for(int i = 0; i < M; ++i)
	{
	  bool rows[hash_len] = {false};
	  for(int j = 0; j < M; ++j){
	    if(board[j][i] != dot)
	    {
	        if(rows[board[j][i]])
	            return false;
	        else 
	            rows[board[j][i]] = true;
	    }
	  }
	}
	//check inner boxes. 9 * (3 * 3)
	const int N = 3;
	for(int ibox = 0; ibox < M; ++ibox)
	{
		bool box[hash_len] = {false};
		for (int irow = 0; irow < N; ++irow)
		{
			for (int icol = 0; icol < N; ++icol)
			{
				if(board[ibox/N*N + irow][ibox%N*N + icol] != dot &&
					box[board[ibox/N*N + irow][ibox%N*N + icol]])
					return false;
				if(board[ibox/N*N + irow][ibox%N*N + icol] != dot)
				box[board[ibox/N*N + irow][ibox%N*N + icol]] = true;
			}
		}
	}
	return true;
}

这个代码没进行简化,显得很繁琐,这里只是为了明了思路。