【leetcode】 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.

说明:

  • 数独有三个要求:1)每一行的元素都在1-9之间,且同一行内,每一位的数字不重复。2)列与行的要求一致 。3)整个数独的9*9方格,是由9个3*3的9宫格组成的,要求每个九宫格内的数组在1-9之间,且不重复。
  • 程序给定的数独格子中,待填写的部分用‘.’ 来表示,“已经填入的数作为填数判断的提示,称为提示数”(摘自百度百科)。并且默认给定的提示数是正确的,就是说,在此基础上是有解存在的。更多的关于数独的知识,还可以参考<<编程之美>>,里面有讲解。
  • 只需找到一个合法的解即可。

分析:

如果不考虑优化,这个问题就可以对每个尚未填写的位置进行试探,从1-9,然后用上面列举的3个条件去卡,如果满足,就递归进行,如果不行,就把当前填写的试探值抹去(重新复位为‘。)

实现:

bool isValid(vector<vector<char> > &board, int px, int py) {
	int len = board.size();

	//check rows and cols.

	for (int i = 0; i < len; ++i)
	{
		if(i != py && board[px][i] == board[px][py] ||
			i != px && board[i][py] == board[px][py])
			return false;
	}

	//check box
	int basex = px/3 * 3;
	int basey = py/3 * 3;
	for (int i = 0; i < 3; ++i)
		for (int j = 0; j < 3; ++j)
		{
			if( basex + i != px &&
				basey + j != py &&
				board[basex + i][basey + j] == board[px][py])
				return false;
		}
	return true;
}

bool currentSudoku(vector<vector<char> > &board) {

	for (int row = 0; row < 9; ++row)
		for (int col = 0; col < 9; ++col)
		{
			if(board[row][col] == '.')
			{
			    for(char num = '1'; num <= '9'; ++num)
		        {
					board[row][col] = num;
		        	if(isValid(board, row, col) && currentSudoku(board))
		            return true;
					board[row][col] = '.';
		        }
		    	return false;//no number can add in this point.
			}
		}
	return true;
}

void solveSudoku(vector<vector<char> > &board) {
	currentSudoku(board);
}

【leetcode】 Sudoku Solver

时间: 2024-10-12 15:27:28

【leetcode】 Sudoku Solver的相关文章

【leetcode】Sudoku Solver

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 re

【LeetCode】哈希表 hash_table(共88题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [1]Two Sum (2018年11月9日,k-sum专题,算法群衍生题) 给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target . 题解:我这次最大范围的优化代码, hash-table + one pass,时间复杂度 O(N),空间复杂度 O(N).重点在于动态找,一边生成hash-tabl

【LeetCode】回溯法 backtracking(共39题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [10]Regular Expression Matching [17]Letter Combinations of a Phone Number [22]Generate Parentheses (2019年2月13日) 给了一个N,生成N对括号的所有情况的字符串. n = 3 [ "((()))", "(()())", "(

【leetcode刷题笔记】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. 题解:递归.在每个空位

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

【LeetCode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

【LeetCode】Pascal&#39;s Triangle

Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 这题别想用通项公式做,n choose m里面的连乘必然溢出,老老实实逐层用定义做. class Solution { public: vector<vector<

【LeetCode】Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. 思路:第一遍正常复制链表,同时用哈希表保存链表中原始节点和新节点的对应关系,第二遍遍历链表的时候,再复制随机域. 这是一种典型的空间换时间的做法,n个节点,需要大小为O(n