dfs爆搜,从第一个空开始试探
bool check(int sodu[10][10], int n, int m) { int heng = n / 9; int zong = n % 9; int a = heng / 3, b = zong / 3; a *= 3, b *= 3; int i, j; for (i = 0; i < 9; i++) if (sodu[i][zong] == m) return false; for (i = 0; i < 9; i++) if (sodu[heng][i] == m) return false; for (i = a; i < a + 3; i++) { for (j = b; j < b + 3; j++) { if (sodu[i][j] == m) return false; } } return true; } void dfs(int sodu[10][10], int n, int &flag) { if (n > 80) { flag = 1; return; } if (sodu[n / 9][n % 9] == 0) { for (int i = 1; i <= 9; i++) { if (check(sodu, n, i)) { sodu[n / 9][n % 9] = i; dfs(sodu, n + 1, flag); if (!flag) sodu[n / 9][n % 9] = 0; else return; } } } else dfs(sodu, n + 1, flag); }