其他分享
首页 > 其他分享> > LeetCode -- 36.有效的数独

LeetCode -- 36.有效的数独

作者:互联网

链接有效的数独

描述:判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

输入
[
[“5”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],
[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
输出:true

思路:看到题目马上想到的就是hash表,但是我还不会hash,于是想借此机会学习hash表。可是这个时候评论区大家都表示就9个数,用hash有些多余,实际上数组就足以解决问题,甚至使用一个数组就可以,而且

执行用时 : 8 ms, 在所有 C++ 提交中击败了 98.63% 的用户 内存消耗 : 8.7 MB, 在所有 C++ 提交中击败了 100.00% 的用户

在此学习一下大佬的方法,他使用了位运算:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        vector<int> wow(9,0);
        int mux1;
        int mux2;
        int mux3;
        int box_index;

        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                if(board[i][j] == '.'){
                    continue;
                }
                mux1 = 0x01 << (board[i][j] - '1');
                mux2 = 0x01 << 9 << (board[i][j] - '1');
                mux3 = 0x01 << 9 << 9 << (board[i][j] - '1');
                box_index = (i/3) * 3 + j/3;
                if((wow[i]&mux1) != mux1 && (wow[j]&mux2) != mux2 && (wow[box_index]&mux3) != mux3){
                    wow[i] = wow[i]|mux1;
                    wow[j] = wow[j]|mux2;
                    wow[box_index] = wow[box_index]|mux3;
                }
                else{
                    return false;
                }
            }
        }
        return true;
    }
};

其中使用 box_index = (row / 3) * 3 + columns / 3枚举子数独

没有使用hash,用二维数组做出来的,加上了注释:

class Solution{
public:
	bool isValidSudoku(vector<vector<char>>& board) {
		vector<vector<int>> row(9, vector<int>(9,0)); //初始化行元素,第一个参数9表示开了九个存储空间,后者表示某行有9个数,每个数数量初始化为0 
		vector<vector<int>> col(9, vector<int>(9,0)); //初始化列元素,第一个参数9表示开了九个存储空间,后者表示某行有9个数,每个数数量初始化为0 
		vector<vector<int>> box(9, vector<int>(9,0)); //初始化子数独,第一个参数9表示开了九个存储空间,后者表示某行有9个数,每个数数量初始化为0 
		
		for(int i = 0; i < 9 ; i++)
		{
			for(int j = 0; j < 9 ; j++)
			{
				if(board[i][j] == '.') //遇到空值,直接跳过后续操作进行下一次循环 
				{
					continue;
				}
				int val = board[i][j] - '1'; //获取非空值的值,将其转化为int类型(这里-'1'是因为vector里的九个数并非1~9而是0~8 
				int box_index = (i/3) * 3 + j/3; //得到子数独(3*3)的序号 
				if(row[i][val] == 0 && col[j][val] == 0 && box[box_index][val] == 0) //查看val在同一行(i)、同一列(j)、同一子数独中其他位置出现没 
				{
					row[i][val] = 1; //出现过的话就全部做记号 
					col[j][val] = 1;
					box[box_index][val] = 1;
				}
				else //出现过直接返回false 
				{
					return false;
				}
			}
		}
		return true;
	}
};

在此特地为vector做一点笔记:

标签:box,index,val,--,wow,int,vector,LeetCode,数独
来源: https://blog.csdn.net/llap_wyx/article/details/113791342