leetcode 36.有效的数独

发布于:2024-12-19 ⋅ 阅读:(11) ⋅ 点赞:(0)

1.题目要求:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
2.题目步骤:
写好判断函数
3.题目代码:

class Solution {
public:
    bool isvalid(vector<vector<char>>& board,char num,int row,int col){
        //先找左下标
        int leftrow = row - 1;
        while(leftrow >= 0){
            if(board[leftrow][col] == num){
                return false;
            }
            leftrow--;
        }
        //再找右下标
        int rightrow = row + 1;
        while(rightrow < 9){
            if(board[rightrow][col] == num){
                return false;
            }
            rightrow++;
        }
        //先找上下标
        int upcol = col - 1;
        while(upcol >= 0){
            if(board[row][upcol] == num){
                return false;
            }
            upcol--;
        }
        //再找下下标
        int downcol = col + 1;
        while(downcol < 9){
            if(board[row][downcol] == num){
                return false;
            }
            downcol++;
        }
        //在分区jiu'gong'ge
        int part_row = row;
        while(part_row != 0&&part_row != 3&&part_row != 6){
            part_row--;
        } 
        int part_col = col; 
        while(part_col != 0&&part_col != 3&&part_col != 6){
            part_col--;
        }
        for(int i = part_row;i <= part_row + 2;i++){
            for(int j = part_col;j <= part_col + 2;j++){
                if(board[i][j] != '.'&&i != row && j != col){
                    if(board[i][j] == num){
                        return false;
                    }
                }
            }
        }
        return true; 
    }
    bool isValidSudoku(vector<vector<char>>& board) {
        for(int i = 0;i < board.size();i++){
            for(int j = 0;j < board[i].size();j++){
                if(board[i][j] != '.'){
                    bool ret = isvalid(board,board[i][j],i,j);
                    if(ret == false){
                        return false;
                    } 
                }
            }
        }
        return true;
    }
};

网站公告

今日签到

点亮在社区的每一天
去签到