zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    这题看似很复杂,其实很无脑,因为也无需判断是否是可解的sudoku board。遍历这个board,找到不为空的位置时,分别考察其行,列和3x3;如果出现重复则为非法,遍历完毕全部通过检查则为合法。

        bool isValidSudoku(vector<vector<char> > &board) {
                unordered_set<int> column;
        unordered_set<int> square;
        unordered_set<int> row;
     
        
        // check for colum
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char item = board[j][i];
                if (item != '.') {
                    int num = atoi(&item);
                    if (column.find(num) == column.end()){
                        column.insert(atoi(&item));
                    }
                    else {
                        return false;
                    }
                }
            }
            column.clear();
        }
    
        // check for row
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char item = board[i][j];
                if (item != '.') {
                    int num = atoi(&item);
                    if (row.find(num) == row.end()) {
                        row.insert(num);
                    }
                    else {
                        return false;
                    }
                }
            }
            row.clear();
        }
        
        // check for 3x3
        for (int offsetY = 0; offsetY < 3; offsetY++) {
            for (int offsetX = 0; offsetX < 3; offsetX++) {
                
                for (int i = 3*offsetY; i < 3*offsetY+3; i++) {
                    for (int j = 3*offsetX; j < 3*offsetX+3; j++) {
                        char item = board[i][j];
                        if (item != '.') {
                            int num = atoi(&item);
                            if (square.find(num) == square.end()) {
                                square.insert(num);
                            }
                            else {
                                return false;
                            }
                        }
                    }
                }
                square.clear();
                
            }
        }
        
        return true;
        }
    
  • 相关阅读:
    比特币--私钥->公钥->钱包地址
    密码字典收集-
    P2P原理和NAT打洞
    SpringBoot
    Spring核心-IOC-AOP-模版
    ZK典型应用场景
    ZK使用
    [重新做人]从头学习JAVA SE——java.util
    CSVWriter 写 csv文档流程
    SpringBoot的启动流程
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4072725.html
Copyright © 2011-2022 走看看