Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

A sudoku puzzle...

...and its solution numbers marked in red.

这题跟N-Queens是一个套路,回溯法尝试所有解。

需要注意的区别是:

本题找到解的处理是return true,因此返回值为bool

N-Queen找到解的处理是保存解,因此返回值为void

对于每个空位'.',遍历1~9,check合理之后往下一个位置递归。

由于这里路径尝试本质上是有序的,即1~9逐个尝试,因此无需额外设置状态位记录已经尝试过的方向。

注意:只有正确达到最终81位置(即成功填充)的填充结果才可以返回,若不然,将会得到错误的填充。

因此辅助函数solve需要设为bool而不是void

class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
solve(board, );
}
bool solve(vector<vector<char> > &board, int position)
{
if(position == )
return true; int row = position / ;
int col = position % ;
if(board[row][col] == '.')
{
for(int i = ; i <= ; i ++)
{//try each digit
board[row][col] = i + '';
if(check(board, position))
if(solve(board, position + ))
//only return valid filling
return true;
board[row][col] = '.';
}
}
else
{
if(solve(board, position + ))
//only return valid filling
return true;
}
return false;
}
bool check(vector<vector<char> > &board, int position)
{
int row = position / ;
int col = position % ;
int gid;
if(row >= && row <= )
{
if(col >= && col <= )
gid = ;
else if(col >= && col <= )
gid = ;
else
gid = ;
}
else if(row >= && row <= )
{
if(col >= && col <= )
gid = ;
else if(col >= && col <= )
gid = ;
else
gid = ;
}
else
{
if(col >= && col <= )
gid = ;
else if(col >= && col <= )
gid = ;
else
gid = ;
} //check row, col, subgrid
for(int i = ; i < ; i ++)
{
//check row
if(i != col && board[row][i] == board[row][col])
return false; //check col
if(i != row && board[i][col] == board[row][col])
return false; //check subgrid
int r = gid/*+i/;
int c = gid%*+i%;
if((r != row || c != col) && board[r][c] == board[row][col])
return false;
}
return true;
}
};

check的另一种实现方式如下:

bool check(vector<vector<char> > &board, int pos)
{
int v = pos/;
int h = pos%;
char target = board[v][h];
//row
for(vector<char>::size_type st = ; st < ; st ++)
{
if(st != h)
{
if(target == board[v][st])
return false;
}
} //col
for(vector<char>::size_type st = ; st < ; st ++)
{
if(st != v)
{
if(target == board[st][h])
return false;
}
} //subgrid
int beginx = v/*;
int beginy = h/*;
for(int i = beginx; i < beginx+; i ++)
{
for(int j = beginy; j < beginy+; j ++)
{
if(i != v && j != h)
{
if(target == board[i][j])
return false;
}
}
} return true;
}

【LeetCode】37. Sudoku Solver的更多相关文章

  1. [Leetcode][Python]37: Sudoku Solver

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 37: Sudoku Solverhttps://oj.leetcode.co ...

  2. 【LeetCode题意分析&解答】37. Sudoku Solver

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

  3. 【leetcode】Valid Sudoku

    题目简述: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board cou ...

  4. leetcode problem 37 -- Sudoku Solver

    解决数独 Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated ...

  5. 【LeetCode】 Valid Sudoku

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

  6. 【leetcode】Valid Sudoku (easy)

    题目:就是判断已有的数字是否冲突无效,若无效返回flase 有效返回true 不要求sudo可解 用了char型的数字,并且空格用‘.'来表示的. 思路:只要分别判断横向 竖向 3*3小块中的数字是否 ...

  7. 【LEETCODE】37、122题,Best Time to Buy and Sell Stock II

    package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...

  8. 【LeetCode】36. Valid Sudoku 解题报告(Python)

    [LeetCode]36. Valid Sudoku 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址 ...

  9. leetcode 37. Sudoku Solver 36. Valid Sudoku 数独问题

    三星机试也考了类似的题目,只不过是要针对给出的数独修改其中三个错误数字,总过10个测试用例只过了3个与世界500强无缘了 36. Valid Sudoku Determine if a Sudoku ...

随机推荐

  1. Gson全解析(下)-Gson性能分析

    前言 在之前的学习中,我们在Gson全解析(上)Gson使用的基础到分别运用了JsonSerializer和JsonDeserializer进行JSON和java实体类之间的相互转化. 在Gson全解 ...

  2. 如何利用启明星Portal门户系统的Page模块构建文档库

    利用启明星门户系统的Page模块构架可以搭建企业内部的文档管理系统. (一)应用背景 企业内部通常都会使用共享网盘的方式来存放不同部门之间的文档,例如管理员在服务器上对人事部门增加人事部文档文件夹. ...

  3. libevent的hello world程序

    照着例子写了一个简单的libevent hello world代码: #include <sys/signal.h> #include <event.h> void signa ...

  4. 基于zabbix的Redis、Sentinel、Slave多实例自动发现监控

    约定 保证whereis redis-cli 能够正确返回redis-cli程序的路径 保证 redis的配置文件在模板宏{$REDIS_SERVER_CONFIG_PATH}的路径,并且后缀名 为. ...

  5. jwplayer 隐藏属性方法记载

    jwplayer().getPosition(): //播放了多少秒 jwplayer('playerdiv').play(); || jwplayer(0).play(true / false); ...

  6. C# 实现的异步 Socket 服务器

    介绍 我最近需要为一个.net项目准备一个内部线程通信机制. 项目有多个使用ASP.NET,Windows 表单和控制台应用程序的服务器和客户端构成. 考虑到实现的可能性,我下定决心要使用原生的soc ...

  7. 2.Dynamic Programming on Stolen Values【dp】

    Problem: There are  n houses built in a line, each of which contains some value in it. A thief is go ...

  8. python 初步学习

    疑惑1:windows下的python  如何设置显示汉字 推荐几个学习网址,也方便自己以后查看: http://pmghong.blog.51cto.com/3221425/d-10 www.w3c ...

  9. Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

      Error:(1, 0) The android gradle plugin version 3.0.0-alpha1 is too old, please update to the lates ...

  10. SQL Server 附加数据库提示5120错误

    怎么样是不是跟你的错误是一样的,心里是不是有点小激动? T_T 终于有办法了!!!! 第一步先关掉你的SQLserver 然后在菜单上找找到SQLSERVER右键选择“以管理员运行” 第二步给你的数据 ...