Valid Sudoku问题及解法

来源:互联网 发布:网络盗刷信用卡什么罪 编辑:程序博客网 时间:2024/06/01 10:47

问题描述:

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.

问题分析:

一个数独板是否有效,就要看以下三个方面:

每一行没有重复的;

每一列没有重复的;

每一个子九宫格没有重复的。


过程详见代码:

class Solution {public:    bool isValidSudoku(vector<vector<char>>& board) {        vector<vector<int> > box(9,vector<int>(10,0));                for(int i = 0; i < 9; i++)        {        vector<int> row(10,0);        vector<int> col(10,0);        for(int j = 0; j < 9;j++)        {        if(board[i][j] != '.'){row[board[i][j] - '0']++;if(row[board[i][j] - '0'] > 1) return false;int id = i / 3 * 3 + j / 3;if(box[id][board[i][j] - '0']) return false;box[id][board[i][j] - '0'] = 1;}        if(board[j][i] != '.'){col[board[j][i] - '0']++;if(col[board[j][i] - '0'] > 1) return false;}}}return true;    }};


原创粉丝点击