本文共 689 字,大约阅读时间需要 2 分钟。
DFS1#includeusing namespace std;int n, pre;int vis[23];int p[23];int cnt;int kcase;bool isPrime(int num){ for(int i = 2; i*i <= num; ++i){ if(num%i == 0) return false; } return true;}void dfs(int cur, int pre, int s){ if(!isPrime(cur+pre)) return; if(s == n && isPrime(cur+1)){ int flag = 1; for(int i = 0; i < n; ++i){ if(flag){ cout << p[i]; flag = 0; } else{ cout <<" "<
采用数组 记录 类似八皇后处理 正确性是基于 p数组 随着深度变化 不断被改变
DFS2
void dfs(int s){ if(s == n && isPrime(p[s-1]+1)){ int flag = 1; for(int i = 0; i < s; ++i){ if(flag){ cout << p[i]; flag = 0; } else{ cout <<" "<第二种DFS一定注意 s++ 位置 如果采用dfs(s+1)则 当s+1 == n时候 s == n-1 此时回退到起点 s将退为0 而不是1
转载地址:http://zmimi.baihongyu.com/