[leetcode] 36. Valid Sudoku 解题报告

题目链接:https://leetcode.com/problems/valid-sudoku/

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.


思路:分别判断九宫和行列不要出现重复的数即可。这么简单的题目,判断条件还是出现了几次错误,哭,还有三题就把easy的题写完了,已经121道了,奋斗

代码如下:

class Solution {
public:
    bool checkSqure(vector<vector<char>>& board, int row1, int row2, int col1, int col2)//检查九宫
    {
        int hash[10];
        memset(hash, 0, sizeof(hash));
        for(int i = row1; i<= row2; i++)
            for(int j = col1; j <= col2; j++)
            {
                if(board[i][j] == '.') continue;
                if(hash[board[i][j] - '0']==0)
                    hash[board[i][j] - '0']++;
                else
                    return false;
            }
        return true;
    }
    bool isValidSudoku(vector<vector<char>>& board) {
        for(int i = 0; i< 3; i++)
            for(int j =0; j< 3; j++)
            if(checkSqure(board, i*3, i*3+2, j*3, j*3+2) == false)
                return false;
        cout << "hello" << endl;
        int hashRow[10], hashCol[10];
        for(int i = 0; i< 9; i++)//检查行
        {
            memset(hashRow, 0, sizeof(hashRow));
            for(int j = 0; j< 9; j++)
            {
                if(board[i][j] == '.') continue;
                if(hashRow[board[i][j] - '0']==0)
                    hashRow[board[i][j] - '0']++;
                else
                    return false;
            }
        }
        for(int i = 0; i< 9; i++)//检查列
        {
            memset(hashCol, 0, sizeof(hashCol));
            for(int j = 0; j< 9; j++)
            {
                if(board[j][i] == '.') continue;
                if(hashCol[board[j][i] - '0']==0)
                    hashCol[board[j][i] - '0']++;
                else
                    return false;
            }
        }
        
        return true;
    }
};


你可能感兴趣的:(LeetCode,算法,String)