博客
关于我
Leetcode 36. 有效的数独
阅读量:244 次
发布时间:2019-03-01

本文共 2697 字,大约阅读时间需要 8 分钟。

判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

上图是一个部分填充的有效的数独。

数独部分空格内已填入了数字,空白格用 '.' 表示。

示例 1:

输入:[  ["5","3",".",".","7",".",".",".","."],  ["6",".",".","1","9","5",".",".","."],  [".","9","8",".",".",".",".","6","."],  ["8",".",".",".","6",".",".",".","3"],  ["4",".",".","8",".","3",".",".","1"],  ["7",".",".",".","2",".",".",".","6"],  [".","6",".",".",".",".","2","8","."],  [".",".",".","4","1","9",".",".","5"],  [".",".",".",".","8",".",".","7","9"]]输出: true

示例 2:

输入:[  ["8","3",".",".","7",".",".",".","."],  ["6",".",".","1","9","5",".",".","."],  [".","9","8",".",".",".",".","6","."],  ["8",".",".",".","6",".",".",".","3"],  ["4",".",".","8",".","3",".",".","1"],  ["7",".",".",".","2",".",".",".","6"],  [".","6",".",".",".",".","2","8","."],  [".",".",".","4","1","9",".",".","5"],  [".",".",".",".","8",".",".","7","9"]]输出: false解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。     但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。

说明:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。
  • 给定数独序列只包含数字 1-9 和字符 '.' 。
  • 给定数独永远是 9x9 形式的。

 

这是一个比较经典的二维数组遍历题目

class Solution {public:    bool isValidSudoku(vector
>& board) { int flag[10]; // flag[0]放1的个数,flag[1]放2的个数 for(int i=0;i<9;i++) { memset(flag,0,sizeof(int)*9); for(int j=0;j<9;j++) { if(board[i][j]!='.') { if(flag[board[i][j]-'1']) return false; // 如果已经有数,则重复 flag[board[i][j]-'1'] = 1; } } } for(int i=0;i<9;i++) { memset(flag,0,sizeof(int)*9); for(int j=0;j<9;j++) { if(board[j][i]!='.') { if(flag[board[j][i]-'1']) return false; flag[board[j][i]-'1'] = 1; } } } int row,col=0; for(row=0;row<9;) { memset(flag,0,sizeof(int)*9); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(board[i+row][j+col]!='.') { if(flag[board[i+row][j+col]-'1']) return false; flag[board[i+row][j+col]-'1']=1; } } } if(col==6) { col=0; row+=3; } else { col+=3; } } return true; }};

 

转载地址:http://nghv.baihongyu.com/

你可能感兴趣的文章
mysql 随机数 rand使用
查看>>
MySQL 面试题汇总
查看>>
MySQL 面试,必须掌握的 8 大核心点
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>
MySQL 高性能优化规范建议
查看>>
mysql 默认事务隔离级别下锁分析
查看>>
Mysql--逻辑架构
查看>>
MySql-2019-4-21-复习
查看>>
mysql-5.6.17-win32免安装版配置
查看>>
mysql-5.7.18安装
查看>>
MySQL-Buffer的应用
查看>>
mysql-cluster 安装篇(1)---简介
查看>>
mysql-connector-java.jar乱码,最新版mysql-connector-java-8.0.15.jar,如何愉快的进行JDBC操作...
查看>>
mysql-connector-java各种版本下载地址
查看>>
mysql-EXPLAIN
查看>>
MySQL-Explain的详解
查看>>
mysql-group_concat
查看>>
MySQL-redo日志
查看>>
MySQL-【1】配置
查看>>
MySQL-【4】基本操作
查看>>