Day23: [LeetCode中等] 36. 有效的数独

Day23: [LeetCode中等] 36. 有效的数独

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/valid-sudoku/

思路:

我刚开始看到这题目的想法是:遍历三次二维数组,然后对应三个条件。但是后来发现遍历一次就可以了(其实和遍历三次的时间复杂度是一样的,毕竟是加性的嘛,但是效率肯定高很多),遍历的同时,把值记录在三个二维数组中,这三个二维数组对应的就是三个条件。flag=(i/3)*3+j/3这句就是为了得到当前标记的所属方块序号。

代码:

dirty code凑合看吧

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int row[9][10]={0};
        int col[9][10]={0};
        int mark[9][10]={0};
        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                if(board[i][j]=='.') continue;
                int flag=(i/3)*3+j/3,x=board[i][j]-'0';
                if(mark[flag][x]==0) mark[flag][x]++;
                else return false;
                if(col[j][x]==0) col[j][x]++;
                else return false;
                if(row[i][x]==0) row[i][x]++;
                else return false;
            }
        }
        return true;
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 526

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103201221