乱七八糟代码合集٩(๑>◡<๑)۶
1.全排列
#include<bits/stdc++.h> using namespace std; int n = 3; bool hashtable[100] = {false}; int P[100] = {-1}; int count_num = 0; void f(int index){ if(index == n + 1){ for (int i = 1; i <= n; i++){ printf("%d ", P[i]); } count_num++; printf("\n"); return; } for (int x = 1; x <= n; x++){ if (hashtable[x] == false){ P[index] = x; hashtable[x] = true; f(index + 1); hashtable[x] = false; } } } int main(){ f(1); printf("\ncount=%d", count_num); return 0; }
2.八皇后-暴力
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n = 4; 4 int P[9] = {0}; 5 int cntnum = 0; 6 bool tablehash[9] = {false}; 7 8 void f(int index){ 9 if (index == n + 1){ 10 bool flag = true; 11 for (int i = 1; i <= n; i++){ 12 for (int j = i + 1; j <= n; j++){ 13 if (abs(i - j) == abs(P[i] - P[j])){ 14 flag = false; 15 } 16 } 17 } 18 if (flag){ 19 for (int k= 1; k <= n; k++){ 20 printf("%d ", P[k]); 21 } 22 printf("\n"); 23 cntnum++; 24 } 25 return; 26 } 27 for (int i = 1; i <= n; i++){ 28 if (tablehash[i] == false){ 29 P[index] = i; 30 tablehash[i] = true; 31 f(index + 1); 32 tablehash[i] = false; 33 } 34 } 35 } 36 int main(){ 37 f(1); 38 printf("%d", cntnum); 39 return 0; 40 }
3.八皇后-回溯
#include<bits/stdc++.h> using namespace std; int n = 9; int P[30] = {0}; int cntnum = 0; bool tablehash[30] = {false}; void f(int index){ if (index == n + 1){ cntnum++; for (int k = 1; k <= n; k++){ printf("%d ", P[k]); } printf("\n"); return; } for (int i = 1; i <= n; i++){ bool flag = true; if (tablehash[i] == false){//假如第i行没有皇后, 即放在第 i 行第 index 列 for (int j = 1; j < index; j++){//遍历和以前的皇后是否合法 if (abs(index - j) == abs(P[j] - i)){ flag = false; break; } } if (flag){//目前可以在第i行第index列放入皇后 P[index] = i; tablehash[i] = true; f(index + 1); tablehash[i] = false; } } } } int main(){ f(1); //printf("%d", cntnum); printf("%d", cntnum); return 0; }
(未完待续~)