之前虽然学过搜索,感觉忘了很多,所以写一遍博客来回忆一下。
深度优先搜索(DFS)和广度优先搜索(BFS)是基本的暴力技术。
一般来说用队列这种数据结构来实现BFS,用栈这种数据结构来实现DFS(用递归来实现)。
经典BFS:
贴一个🔗http://lx.lanqiao.cn/problem.page?gpid=T291
AC代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include<bits/stdc++.h> using namespace std;
int m, n; int maze[505][505]; bool vis[505][505];
int dir[4][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}}; char r[4] = {'D', 'L', 'R', 'U'};
struct node { int x; int y; int step; string road; };
bool check(int x, int y) { if(x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && maze[x][y] == 0) return true; return false; }
void BFS(int x, int y) { queue <node> q; node st, ne; st.x = x; st.y = y; st.step = 0; st.road = ""; vis[x][y] = true; q.push(st); while(!q.empty()) { st = q.front(); q.pop(); if(st.x == n - 1 && st.y == m - 1) { cout << st.step << endl << st.road << endl; return; } for(int i = 0; i < 4; ++i) { ne.x = st.x + dir[i][0]; ne.y = st.y + dir[i][1]; if(check(ne.x, ne.y)) { vis[ne.x][ne.y] = true; ne.step = st.step + 1; ne.road = st.road + r[i]; q.push(ne); } } } }
int main() { cin >> n >> m; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { scanf("%1d", &maze[i][j]); } } BFS(0, 0); return 0; }
|