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. OBjective-C:文件管理类NSFileManager

    文件管理类NSFileManager类:对文件进行创建.复制.重命名.删除等,一般不对文件内容进行操作. NSData类和NSMutableData类:相当于数据缓冲区  NSFileManager是 ...

  2. socket函数send和recv函数

    转自:http://www.cppblog.com/aaxron/archive/2012/04/27/172891.html 在发送端,一次发送4092个字节,在接收端,一次接收4092个字节,但是 ...

  3. STM32串口的设置和库函数的介绍

    串口设置的一般步骤可以总结为如下几个: 1) 串口时钟使能, GPIO时钟使能  2) 串口复位 3)GPIO 端口模式设置 4) 串口参数初始化  5) 开启中断并且初始化 NVIC(如果需要开启中 ...

  4. Python中scatter函数参数用法详解

    1.scatter函数原型 2.其中散点的形状参数marker如下: 3.其中颜色参数c如下: 4.基本的使用方法如下: #导入必要的模块 import numpy as np import matp ...

  5. 我的SQL里哪个语句占用的CPU最多?

    可以使用下面的语句来得到 SELECT SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, ( (CASE qs.statement_end_off ...

  6. 配置sonarqube+maven

    Maven与Sonar配合使用  准备工作:下载sonarqube源码即可  步骤:      1).安装sonar 解压,启动sonarqube-4.1\bin\windows-x86-32目录下的 ...

  7. 按示例学python:使用python抓取网页正文

    平时打开一个网页,除了文章的正文内容,通常会有一大堆的导航,广告和其他方面的信息.本博客的目的,在于说明如何从一个网页中提取出文章的正文内容,而过渡掉其他无关的的信息. 这里先看看 demo : ht ...

  8. C#.NET常见问题(FAQ)-SplitPanel如何设置上下和左右

    定位到Orientation属性即可     更多教学视频和资料下载,欢迎关注以下信息: 我的优酷空间: http://i.youku.com/acetaohai123   我的在线论坛: http: ...

  9. Singular value encountered in calculation for ROI

    在ENVI中对一幅TM影像进行监督分类,在进行compute ROI separability时提示Singular value encountered in calculation for ROI, ...

  10. 把thinkphp项目拷贝到其他电脑上报错

    提示 include(***\ThinkPHP\Library/Think/Log.class.php): failed to open stream 把Application\Runtime文件夹里 ...