判断一个数独是否合法,未填的空格用字符 ' . ' 表示。该数独有解并不是必要的。

e.g. 如图合法数独,输入

["53..7....","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"]

返回 true。

我依然使用死办法解决,而且进行了输入合法性判断,即必须为 1 ~ 9 的数字或 ' . ' 。

 bool isValidSudoku(vector<vector<char>>& board) {
vector<char> row, column, subbox;
for (int i = ; i < ; ++i) {
row.clear();
column.clear();
row = board[i];
if (!isValid(row))
return false;
for (int j = ; j < ; ++j) {
column.push_back(board[j][i]);
}
if (!isValid(column))
return false;
}
for (int i = ; i <= ; i = i + ) {
for (int j = ; j <= ; j = j + ) {
subbox.clear();
subbox.push_back(board[i][j]); subbox.push_back(board[i][j+]); subbox.push_back(board[i][j+]);
subbox.push_back(board[i+][j]); subbox.push_back(board[i+][j+]); subbox.push_back(board[i+][j+]);
subbox.push_back(board[i+][j]); subbox.push_back(board[i+][j+]); subbox.push_back(board[i+][j+]);
if (!isValid(subbox))
return false;
}
}
return true;
} bool isValid(vector<char> &t) {
sort(t.begin(), t.end());
for (int i = ; i < ; ++i) {
if (((t[i] < '' || t[i] > '') && t[i] != '.') || (i > && t[i] == t[i - ] && t[i] != '.'))
return false;
}
return true;
}

答案巧妙的做法如下

 bool isValidSudoku(vector<vector<char>>& board) {
bool row[][] = {false}, col[][] = {false}, box[][] = {false};
for (int i = ; i < ; i++) {
for (int j = ; j < ; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '' - , k = i / * + j / ;
if (row[i][num] || col[j][num] || box[k][num]) return false;
row[i][num] = col[j][num] = box[k][num] = true;
}
}
}
return true;
}

num = board[i][j] - '0' - 1 的思路就是用一个新 bool 型数组(初始化全为 false)判断原数组是否有重复元素。

k = i / 3 * 3 + j / 3 将原来 9 * 9 的方格映射到 3 * 3 的方格中!

0 | 1 | 2
3 | 4 | 5
6 | 7 | 8

例如 i = 5,j = 6 (第 5 行 第 6 列)时,k = 5 / 3 * 3 + 6 / 3 = 1 * 3 + 2 = 5,在 box[5][] 这个数组里进行判断。

这种方法更常规的用法见下。

这个Java实现也很巧妙

 public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9; i++) {
Set<Character> rows = new HashSet<>();
Set<Character> cols = new HashSet<>();
Set<Character> cubes = new HashSet<>();
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.' && !rows.add(board[i][j])) return false;
if (board[j][i] != '.' && !cols.add(board[j][i])) return false;
int colStart = 3 * (i % 3), rowStart = 3 * (i / 3);
int colOffset = j % 3, rowOffset = j / 3; // 偏移
int row = rowStart + rowOffset, col = colStart + colOffset;
if (board[row][col] != '.' && !cubes.add(board[row][col]) ) return false;
}
}
return true;
}

HashSet 的 add(E e) 方法用于将指定元素添加到这个 HashSet,若此 Set 已经包含该元素,则直接返回 false。

%/ 操作符对于矩阵遍历问题很有帮助。

使用 % 作水平遍历,即计算列坐标偏移。因为 j 每增加 ,j % 3 也增加 然后重置

使用  /  作竖直遍历,即计算行坐标偏移。因为 j 每增加 ,j / 3 才能增加

通过 0 ~ 8 的 j 即可遍历一个 9 * 9 矩阵的一个 3 * 3 子块。如何继续遍历下一个子块呢?就需要用外层循环 0 ~ 8 的 i 实现。

依然使用 % 水平遍历到下一个子块,colStart = 3 * (i % 3) ,× 3 是因为下一个子块在 3 列之后,第一个子块的起始是 (0, 0),第二个子块的起始是 (0, 3) 而不是 (0, 1)。

e.g.

i = 2 时,j 从 0 ~ 8,

rowStart = 3 * (2 / 3) = 0                                      colStart = 3 * (2 % 3) = 6

rowOffset = j / 3 = 0,0,0, 1,1,1, 2,2,2                   colOffset = j % 3 = 0,1,2, 0,1,2, 0,1,2

对应了 board 矩阵中的

(0+0, 6+0) (0+0, 6+1) (0+0, 6+2)
(0+1, 6+0) (0+1, 6+1) (0+1, 6+2)
(0+2, 6+0) (0+2, 6+1) (0+2, 6+2)

(0,6) (0,7) (0,8)
(1,6) (1,7) (1,8)
(2,6) (2,7) (2,8)

这个 Sub-Box。

【LeetCode】数独的更多相关文章

  1. [LeetCode] Sudoku Solver 求解数独

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  2. [LeetCode] Valid Sudoku 验证数独

    Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be ...

  3. LeetCode:36. Valid Sudoku,数独是否有效

    LeetCode:36. Valid Sudoku,数独是否有效 : 题目: LeetCode:36. Valid Sudoku 描述: Determine if a Sudoku is valid, ...

  4. LeetCode 37 Sudoku Solver(求解数独)

    题目链接: https://leetcode.com/problems/sudoku-solver/?tab=Description   Problem : 解决数独问题,给出一个二维数组,将这个数独 ...

  5. LeetCode 36 Valid Sudoku(合法的数独)

    题目链接: https://leetcode.com/problems/valid-sudoku/?tab=Description   给出一个二维数组,数组大小为数独的大小,即9*9  其中,未填入 ...

  6. [LeetCode] “全排列”问题系列(一) - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题

    一.开篇 Permutation,排列问题.这篇博文以几道LeetCode的题目和引用剑指offer上的一道例题入手,小谈一下这种类型题目的解法. 二.上手 最典型的permutation题目是这样的 ...

  7. “全排列”问题系列(一)[LeetCode] - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题

    转:http://www.cnblogs.com/felixfang/p/3705754.html 一.开篇 Permutation,排列问题.这篇博文以几道LeetCode的题目和引用剑指offer ...

  8. Leetcode之回溯法专题-37. 解数独(Sudoku Solver)

    Leetcode之回溯法专题-37. 解数独(Sudoku Solver) 编写一个程序,通过已填充的空格来解决数独问题. 一个数独的解法需遵循如下规则: 数字 1-9 在每一行只能出现一次.数字 1 ...

  9. [LeetCode] 37. Sudoku Solver 求解数独

    Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy  ...

  10. [LeetCode] 36. Valid Sudoku 验证数独

    Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to th ...

随机推荐

  1. demoshow - webdemo展示助手

    demoshow - web demo展示助手 动态图演示页面: http://www.cnblogs.com/daysme/p/6790829.html 一个用来展示前端网页demo的小“助手”,提 ...

  2. HDU 1251 统计难题(字典树模板题)

    http://acm.hdu.edu.cn/showproblem.php?pid=1251 题意:给出一些单词,然后有多次询问,每次输出以该单词为前缀的单词的数量. 思路: 字典树入门题. #inc ...

  3. Python学习笔记3-string

    More on Modules and their Namespaces Suppose you've got a module "binky.py" which contains ...

  4. MVC杂记

    @{ Layout = “…”} To define layout page Equivalent to asp.NET master-page 要定义相当于ASP.Net母版页的页面布局 @mode ...

  5. JQ遇到$(‘.xxx’).attr(‘display’)一直返回undefined

    jq attr && jq css 1.1 attr() 方法设置或返回被选元素的属性值 我们就题目遇到的问题做一个测试 //html <div class="div1 ...

  6. 【BZOJ】1798: [Ahoi2009]Seq 维护序列seq

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1798 大概就是维护两个标记的线段树模板题. 设定优先级,先乘后加(只是相对的),$push ...

  7. C# 用面向对象的思想去编程

    再接上一篇博文,之前写的两篇博文虽然实现了功能,但是和控件之间的粘性太大,依赖于控件进行操作,所以这篇博文主要用面向对象的思想做一个Demo,将逻辑层与显示层剥离开 首先新建一个窗体文件,搭建界面完毕 ...

  8. 【三】php 数组

    数组 1.数字索引数组:array('a','b','c');  2.访问数组内容 $arr[下标] 3.新增数组元素 $arr[下标]=内容 4.使用循环访问数组 //针对数字索引 $arr=arr ...

  9. oracle中sql优化

    问题描述:刚开始做项目的时候没啥感觉,只用能出来结果,sql随便写,但是后来用户的数据量达到几万条是,在访问系统,发现很多功能加载都很慢,有的页面一个简单的关联 查询居然要花费30多秒,实在是不能忍, ...

  10. 利用vue-cli3快速搭建vue项目详细过程

    一.介绍 Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统.有三个组件: CLI:@vue/cli 全局安装的 npm 包,提供了终端里的vue命令(如:vue create .vue ...