码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Sudoku

时间:2015-10-18 14:06:18      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

 

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) {
        set<char> row, col, box;
        for(int i = 0; i < 9; i++)
        {
            for(int j = 0; j < 9; j++)
            {
                if(board[i][j] != .)
                    {
                        if(row.find(board[i][j]) != row.cend())
                            return false;
                        else 
                            row.insert(board[i][j]);
                    }
                if(board[j][i] != .)
                    {
                        if(col.find(board[j][i]) != col.cend())
                            return false;
                        else 
                            col.insert(board[j][i]);
                    }
                if(board[(i / 3) *3  + j / 3][(i % 3) * 3 + j % 3] != .)
                {
                    if(box.find(board[(i / 3) *3  + j / 3][(i % 3) * 3 + j % 3]) != box.cend())
                        return false;
                    else
                        box.insert(board[(i / 3) *3  + j / 3][(i % 3) * 3 + j % 3]);
                }
            }
            row.clear();
            col.clear();
            box.clear();
        }
        return true;
    }
};
  • 每一行,每一列,每一个九格,保存一个set,如果发现有重复就返回
  • 主要是从i,j推出九格的位置
  • i/3为第几行 i%3为第几列
  • 每一次判断完都需要把set清空,重新开始

Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4889384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!