数独问题

来源:互联网 发布:linux搭建lamp 编辑:程序博客网 时间:2024/05/14 02:10
#include <stdio.h>#define n 9int a[n][n] = {0, 0, 5, 3, 0, 0, 0, 0, 0,8, 0, 0, 0, 0, 0, 0, 2, 0,0, 7, 0, 0, 1, 0, 5, 0, 0,4, 0, 0, 0, 0, 5, 3, 0, 0,0, 1, 0, 0, 7, 0, 0, 0, 6,0, 0, 3, 2, 0, 0, 0, 8, 0,0, 6, 0, 5, 0, 0, 0, 0, 9,0, 0, 4, 0, 0, 0, 0, 3, 0,0, 0, 0, 0, 0, 9, 7, 0, 0};int isOk(int x, int y) {//判断该数在行中是否唯一for (int i = 0; i < n; i++) {if (a[x][y] == a[x][i] && i != y && a[x][y] != 0) return 0;}//判断该数在列中是否唯一for (int i = 0; i < n; i++) {if (a[x][y] == a[i][y] && i != x && a[x][y] != 0 ) return 0;}int up = x/3*3;int down = up+3;int left = y/3*3;int right = left+3;//判断在方形中该数是否唯一for (int i = up; i < down; i++) {for (int j = left; j < right; j++) {if (x!=i || y!=j) {if (a[x][y] == a[i][j] && a[i][j] != 0)return 0;}}}return 1;}void traceback(int x, int y) {if (a[x][y] != 0) {if (y == n-1) {if (x == n-1) {for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {printf("%d ", a[i][j]);}printf("\n");}} else {traceback(x+1, y);}} else {if (x == n-1) {traceback(0, y+1);} else {traceback(x+1, y);}}} else {for (int value = 1; value < 10; value++) {a[x][y] = value;if (isOk(x, y)) {if (y == n-1) {if (x == n-1) {for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {printf("%d ", a[i][j]);}printf("\n");}} else {traceback(x+1, y);}} else {if (x == n-1) {traceback(0, y+1);} else {traceback(x+1, y);}}}a[x][y] = 0;}}}int main() {int x = 0, y = 0;traceback(x, y);return 0;}

0 0
原创粉丝点击