本文主要是介绍037 - 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.
求数独的解,用递归实现
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);
}
这篇关于037 - Sudoku Solver的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!