浅学一下DFS和BFS,解决全排列和迷宫问题
DFS
全排列
原题链接:https://www.acwing.com/problem/content/844/
- 超过边界return
- 循环遍历,如果已经访问过则continue
- 标记访问过
- 递归下一层
- 回溯清空
#include <stdio.h> #include <iostream> using namespace std; int n; int path[10]; bool st[10] = {false} ; void DFS(int x) { if(x > n) { for (int i = 1; i <= n; i++) cout << path[i] << " "; cout << endl; return; } for(int i = 1; i <= n; i++) { if(st[i] == true) continue; path[x] = i; st[i] = true; DFS(x + 1); st[i] = false; } } int main() { cin >> n; DFS(1); return 0; }
BFS
迷宫问题
原题链接:https://www.acwing.com/problem/content/846/
- 设计一个队列
- 把初始点加入到队列中
- while(q.size())
- 弹出队列的首元素
- 上下左右四个方向遍历
- 如果在范围内,就把该结点放到队列中,距离是上一个结点+1
#include <iostream> #include <queue> #include <algorithm> #include <cstring> using namespace std; int n,m; int map[105][105]; int rec[105][105]; int xx[4] = {-1,0,1,0}; int yy[4] = {0,1,0,-1}; int hh = 0; int tt = 0; typedef pair<int,int> PII; int bfs() { queue<PII> q; rec[1][1] = 0; q.push({1,1}); while(q.size()) { auto t = q.front(); q.pop(); for(int i = 0 ; i < 4; i++) { int x = t.first + xx[i]; int y = t.second + yy[i]; if(x < 1 || x > n || y < 1 || y > m || map[x][y] == 1 || rec[x][y] != 0) continue; q.push({x,y}); rec[x][y] = rec[t.first][t.second] + 1; } } return rec[n][m]; } int main() { cin >> n >> m; for(int i = 1; i <= n; i++) { for(int j = 1; j<= m; j++) cin >> map[i][j]; } cout << bfs() << endl; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】