【搜索】BFS、DFS的综合练习(小鼠迷宫)
2014-02-21 16:21
375 查看
分析:利用bfs可以计算出最短路径的距离len(即移动次数),然后用dfs计算出等于len(移动次数)时有多少种不同的最短路径。
#include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; #define N 100 int mark , map ; struct node{ int x, y; int step; }; int n, m, k; int min_step; int num; int x1, x2, y1, y2; int dir[4][2] = { 0, 1, 0, -1, 1, 0, -1, 0 }; //direction 控制方向 int BFS() { int x, y; queue<node> q; node cur, next; cur.x = x1; cur.y = y1; cur.step = 0; q.push(cur); mark[x1][y1] = 1; while( !q.empty() ) { cur = q.front(); q.pop(); if(cur.x == x2 && cur.y == y2) //如果找到,则肯定是一个找到的,故是最短路径 { return cur.step; } for(int i = 0; i < 4; i++) { //进行方向的改变 next.x = x = cur.x + dir[i][0]; next.y = y = cur.y + dir[i][1]; if(x >= 1 && x <= n && y > 1 && y <= m && mark[x][y] == 0) //判断行进之后是否符合条件 { next.step = cur.step + 1; q.push(next); mark[x][y] = 1; } } } return -1; } void DFS(int x, int y, int c_step) { if(x == x2 && y == y2 && c_step == min_step) { num++; return; } if( (x > x2? x - x2: x2 - x) + (y > y2? y - y2: y2 - y) + c_step > min_step ) //剪枝,如果这枝最优解都比最短路径长,则砍断 { return; } for(int i = 0; i < 4; i++) { int xx, yy; xx = x + dir[i][0]; yy = y + dir[i][1]; if(xx >= 1 && xx <= n && yy >= 1 && yy <= m && map[xx][yy] == 0) { map[xx][yy] = 1; DFS(xx, yy, c_step + 1); map[xx][yy] = 0; } } } int main() { cin >> n >> m >> k; memset(map, 0, sizeof(map)); memset(mark, 0, sizeof(mark)); for(int i = 0; i < k; i++) { int a, b; cin >> a >> b; map[a][b] = 1; mark[a][b] = 1; } cin >> x1 >> y1; cin >> x2 >> y2; min_step = -1; min_step = BFS(); if(min_step == -1) { cout << "No Solution!" << endl; } else { num = 0; DFS(x1, y1, 0); cout << min_step << endl; cout << num << endl; } return 0; }
相关文章推荐
- FZU 1205(小鼠迷宫问题)BFS+DFS的基本综合运用(同一题目中体现两种搜索方法的特点)
- 小鼠迷宫问题【sdut1157】【dfs,bfs综合题目】
- FZU - 1205 小鼠迷宫问题 (bfs+dfs)
- POJ3984 迷宫问题(深搜DFS+广搜BFS)搜索记录坐标,坑
- 基础搜索——dfs,bfs(全排列与迷宫问题)
- matlab练习程序(广度优先搜索BFS、深度优先搜索DFS)
- SDUT1157:小鼠迷宫问题(bfs+dfs)
- FOJ 1205 小鼠迷宫问题【BFS+dfs回溯查找路径】
- 搜索练习3 /poj.org/problem 3984 迷宫问题/bfs 回溯找路经
- 博弈搜索练习-BFS&DFS
- FZU1205/SDUT1157_小鼠迷宫问题(DFS+BFS)
- 搜索专题(DFS&&BFS&&剪枝)HDU 1728-逃离迷宫
- FZU 1205 小鼠迷宫问题 <BFS+DFS>
- SDUT 1157-小鼠迷宫问题(BFS&DFS)
- SDUT 1157-小鼠迷宫问题(BFS&DFS)
- 搜索练习5/poj.org/problem2251/ Dungeon Master/bfs模板
- 杭电2209 翻纸牌游戏 DFS BFS 搜索
- poj2251--Dungeon Master(搜索练习3-三维bfs)
- NYOJ306 走迷宫(dfs+二分搜索)
- 迷宫问题、最短路(BFS,DFS)