关闭

037 - Sudoku Solver

125人阅读 评论(0) 收藏 举报
分类:

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);
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:28464次
    • 积分:1507
    • 等级:
    • 排名:千里之外
    • 原创:124篇
    • 转载:10篇
    • 译文:0篇
    • 评论:0条
    博客专栏