zoukankan      html  css  js  c++  java
  • 36. Valid Sudoku (Array; HashTable)

    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<bool> flag(9, false); //indicate the appearance of 1,2,..., 9
            //check line
            for(int i = 0; i<9; i++)
            {
                for(int j = 0; j<9; j++)
                {
                    if(board[i][j]=='.') continue;
                    if(flag[board[i][j]-'1']) return false;
                    flag[board[i][j]-'1'] = true;
                }
                flag.assign(board.size(),false); //reset the vector
            }
       
            //check column
            for(int j = 0; j<9; j++)
            {
                for(int i = 0; i<9; i++)
                {
                    if(board[i][j]=='.') continue;
                    if(flag[board[i][j]-'1']) return false;
                    flag[board[i][j]-'1'] = true;
                }
                flag.assign(board.size(),false);
            }
       
            //check small square
            for(int i = 0; i < 9; i+=3){
                for(int j = 0; j <9; j+=3){
                    for(int m = 0; m < 3; m++){
                        for(int n = 0; n < 3; n++){
                            if(board[i+m][j+n]=='.') continue;
                            if(flag[board[i+m][j+n]-'1']) return false;
                            flag[board[i+m][j+n]-'1'] = true;
                        }
                    }
                    flag.assign(board.size(),false);
                }
            }
            return true;
        }
    };

     如果没有'.',那么我们可以用以下的方法判断是否valid (参数是某一行,某一列,或是某一个small square的9个元素)

    bool check(vector<int> v) {
        sort(v.begin(), v.end());
        for (int i = 0; i < (int)v.size(); ++i) {
            if (v[i] != i + 1) {
                return false;
            }
        }
        return true;
    }
  • 相关阅读:
    DbUtils类基本使用
    【struts2】ActionContext与ServletActionContext
    Eclipse 菜单---Eclipse教程第04课
    Eclipse 窗口说明---Eclipse教程第03课
    Eclipse 修改字符集---Eclipse教程第02课
    Java 开发环境配置
    Eclipse 安装(Neon 版本2016年)---Eclipse教程第01课
    eclipse中link方式安装插件
    linux 源码安装mysql 5.5
    shell执行mysql命令
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4857030.html
Copyright © 2011-2022 走看看