搜索算法(一)

张开发
2026/4/13 3:53:13 15 分钟阅读

分享文章

搜索算法(一)
深度优先搜索dfs)深度优先的意思就是一条路走到黑如果符合条件就一直走否则就返回上一个节点模板#includeiostream using namespace std; const int N10; int ans[N]; bool mark[N]; int n; void dfs(int u) { //回头的条件 if(un) { for(int i0;in;i)coutans[i] ; puts(); return; } for(int i1;in;i) { if(mark[i]false) { mark[i]true; ans[u]i; dfs(u1); //复原 mark[i]false; ans[u]0; } } } int main() { cinn; dfs(0); return 0; }广度优先搜索bfs最短路#includeiostream #includecstring #includequeue using namespace std; const int N110; typedef pairint,int PII; int map[N][N],mark[N][N]; int dx[4]{-1,0,1,0},dy[4]{0,1,0,-1},n,m,ans; void bfs() { memset(mark,-1,sizeof mark); queuePIIq; q.push({0,0}); mark[0][0]0; while(!q.empty()) { PII topq.front(); for(int i0;i4;i) { int nextop.firstdx[i],neytop.seconddy[i]; if(nex0nexnney0neymmark[nex][ney]-1map[nex][ney]0) { mark[nex][ney]mark[top.first][top.second]1; q.push({nex,ney}); } } q.pop(); } coutmark[n-1][m-1]; } int main() { cinnm; for(int i0;in;i) { for(int j0;jm;j) { scanf(%d,map[i][j]); } } bfs(); }

更多文章