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

leetcode@ [36] Valid Sudoku

时间:2015-11-14 15:04:32      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

技术分享
class Solution {
public:
    vector<int> getIdx(int i, int j) {
        vector<int> idx(4);
        int row, col;
        if(i>=0 && i<=2) {
            idx[0] = 0; idx[1] = 2;
        }
        else if(i>=3 && i<=5) {
            idx[0] = 3; idx[1] = 5;
        }
        else if(i>=6 && i<=8) {
            idx[0] = 6; idx[1] = 8;
        }
        
        if(j>=0 && j<=2) {
            idx[2] = 0; idx[3] = 2;
        }
        else if(j>=3 && j<=5) {
            idx[2] = 3; idx[3] = 5;
        }
        else if(j>=6 && j<=8) {
            idx[2] = 6; idx[3] = 8;
        }
        
        return idx;
    }
    bool checkRowAndColumn(vector<vector<char>>& board, int i, int j) {
        if(i<0 || i>=board.size() || j<0 || j>=board[0].size()) return false;
        
        for(int ni=0;ni<board.size();++ni) {
            if(ni == i || board[ni][j] == .) continue;
            if(board[ni][j] == board[i][j]) return false;
        }
        
        for(int nj=0;nj<board[0].size();++nj) {
            if(nj == j || board[i][nj] == .) continue;
            if(board[i][nj] == board[i][j]) return false;
        }
        
        return true;
    }
    
    bool checkLocal(vector<vector<char>>& board, int i, int j) {
        if(i<0 || i>=board.size() || j<0 || j>=board[0].size()) return false;
        
        vector<int> idx = getIdx(i, j);
        int li = idx[0], ri = idx[1], lj = idx[2], rj = idx[3];
        
        for(int p=li;p<=ri;++p) {
            for(int q=lj;q<=rj;++q) {
                if((i==p && j==q) || board[p][q] == .) continue;
                if(board[i][j] == board[p][q]) return false;
            }
        }
        
        return true;
    }
    bool isValidSudoku(vector<vector<char>>& board) {
        for(int i=0;i<board.size();++i) {
            for(int j=0;j<board[i].size();++j) {
                if(board[i][j] == .) continue;
                if(!checkLocal(board, i, j) || !checkRowAndColumn(board, i, j)) return false;
            }
        }
        return true;
    }
};
View Code

 

leetcode@ [36] Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/4964356.html

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