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

leetcode_36_Valid Sudoku

时间:2015-06-22 11:13:05      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   array   

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.

//方法:时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        bool used[9];
        for(int i = 0; i < 9; i++)  //分别表示从1~9行,和1~9列
        {
            fill(used, used+9, false);  //检查行
            for(int j = 0; j < 9; j++)
            {
                if(!check(board[i][j], used))
                    return false;
            }
            
            fill(used, used+9, false);  //检查列
            for(int j = 0; j < 9; j++) 
            {
                if(!check(board[j][i], used))
                    return false;
            }
        }
        
        for(int i = 0; i < 9; i += 3)  //检查九3*3的正方形
            for(int j = 0; j < 9; j += 3)
            {
                fill(used, used+9, false);
                for(int k = 0; k < 3; k++)
                    for(int l = 0; l < 3; l++)
                    {
                        if(!check(board[i+k][j+l], used))
                            return false;
                    }
            }
        
        return true;
    }
    
    bool check(char ch, bool used[9])
    {
        if(ch == '.')
            return true;
        else if(used[ch - '1'] == false)
        {
            used[ch - '1'] = true;
            return true;
        }
        else if(used[ch - '1'] == true)
            return false;
    }
};










leetcode_36_Valid Sudoku

标签:leetcode   c++   array   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/46591615

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