36. Valid Sudoku

来源:互联网 发布:淘宝客厅装饰物 编辑:程序博客网 时间:2024/06/05 17:42

Problem:

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.

题意是要我们去检查一个数独盘的合法性,也就是同一行,同一列,和同一个九宫格不能存在相同的数字。所以比较简单,就一些嵌套循环就能完成。首先设一个布尔类型的used数组,长度是9来记录某一列或者某一行,或者某个九宫格上数字的使用情况,true为已经用了。例如used[5]表示6这个数字已经使用了。然后如果是什么数字都没有的话,输入是'.'。


Code:(LeetCode运行12ms)

class Solution {public:    bool isValidSudoku(vector<vector<char>>& board) {        bool used[9];            for (int i = 0; i < 9; i++) {            //initial the array of used.            fill(used, used + 9, false);            //check the row.            for (int j = 0; j < 9; j++) {                if (!check(board[j][i], used)) {                    return false;                }            }            fill(used, used + 9, false);            //check the colume.            for (int j = 0; j < 9; j++) {                if (!check(board[i][j], used)) {                    return false;                }            }        }        for (int r = 0; r < 3; r++) {            for (int c = 0; c < 3; c++) {                fill(used, used + 9, false);                for (int i = r * 3; i < r * 3 + 3; i++) {                    for (int j = c * 3; j < c * 3 + 3; j++) {                        if (!check(board[i][j], used)) {                            return false;                        }                    }                }            }        }        return true;    }    bool check(char c, bool *used) {        if (c == '.') {            return true;        }        if (used[c - '1']) {            return false;        }        return used[c - '1'] = true;    }};



原创粉丝点击