037 - Sudoku Solver

原创 2015年11月19日 17:02:38

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.



求数独的解,用递归实现

static int find = 0;
int locok(char **sudu, int x, int y, int num)
{
	int i, j, i1, j1;
	if (sudu[x][y] != '.') return 2;
	/* check row */
	for (i = 0; i < 9; i++)
		if (i != x && sudu[i][y] == num)
			return 0;
	/* check col */
	for (i = 0; i < 9; i++)
		if (i != y && sudu[x][i] == num)
			return 0;
	/* check area */
	i = x / 3 * 3;
	j = y / 3 * 3;
	i1 = i + 3;
	j1 = j + 3;
	for (i = i1 - 3; i < i1; i++) 
		for (j = j1 - 3; j < j1; j++){
			if (i == x && j ==y) continue;
			if (sudu[i][j] == num)
			return 0;
		}

	return 1;
}

int xsudu(char *sudu[], int x, int y)
{
	if (x > 8 || y > 8 || x < 0 || y < 0) return -1;
	int i;
	if (x == 8 && y == 8) {
		for (i = 1; i < 10; i++) {
			int ok = locok(sudu, x, y, i + '0');
			if (!ok) continue;
			if (ok == 1)
				sudu[x][y] = i + '0';
			return find = 1;
		}
	} else {
		for (i = 1; i < 10; i++) {
			int ok = locok(sudu, x, y, i + '0');
			if (!ok) continue;
			if (ok == 1) sudu[x][y] = i + '0';
			xsudu(sudu, y == 8? x + 1:x, y == 8? 0:y + 1);
			if (find) return 0;
			if (ok == 1) sudu[x][y] = '.';
			if (ok == 2) break;
		}	
	}

	return 0;
}

void solveSudoku(char** board, int boardRowSize, int boardColSize) 
{
	find = 0;
	xsudu(board, 0, 0);
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

[LeetCode]037-Sudoku Solver

题目: Write a program to solve a Sudoku puzzle by filling the empty cells.Empty cells are indicated b...

leetcode037:Sudoku Solver

问题分析 数独解法基本靠暴力求解,在所有没有确定的位置对所有可能的解进行尝试,直接暴力解运行时间是153ms。所以在此之前先确定一下唯一解的位置,唯一解有两种类型。 该位置在所在行、列、宫上都满足的...

LeetCode037 Sudoku Solver

详细见:leetcode.com/problems/sudoku-solver Java Solution: github package leetcode; /* * 解数独 ...
  • zxwtry
  • zxwtry
  • 2017年04月05日 15:46
  • 79

[LeetCode] 037. Sudoku Solver (Hard) (C++)

[LeetCode] 037. Sudoku Solver (Hard) (C++)
  • hcbbt
  • hcbbt
  • 2015年03月13日 19:33
  • 1358

Sudoku solver in C++ (数独计算器)

  • 2011年02月08日 23:20
  • 408KB
  • 下载

LeetCode OJ:Sudoku Solver

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

LeetCode Sudoku Solver

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

37. Sudoku Solver

这样的题目一般通过回溯法求解,设置某个空格时,如果该空格无论设置什么数字都无法达到合法状态,那么回溯重新设置上一个空格,详见代码注释。注意,这样的题目一定要想明白每一处细节,才能够作对。代码如下: ...

Leetcode Sudoku Solver My Submissions Question

Leetcode Sudoku Solver My Submissions Question ,本问题主要是使用递归的思想,不断的试探,直到得出结果,同时也得注意记录已有值的方法,主要是横向、纵向、...

Leetcode-Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.Empty cells are indicated by the...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:037 - Sudoku Solver
举报原因:
原因补充:

(最多只允许输入30个字)