nyoj--58 最少步数
2016-03-19 10:21
330 查看
题解
BFS或者DFS最短路。#include <iostream> #include <cstdio> #include <queue> #include <cstring> #include <algorithm> using namespace std; typedef pair<int, int> pii; const int inf = 1 << 30; int maze[9][9] = { {1,1,1,1,1,1,1,1,1}, {1,0,0,1,0,0,1,0,1}, {1,0,0,1,1,0,0,0,1}, {1,0,1,0,1,1,0,1,1}, {1,0,0,0,0,1,0,0,1}, {1,1,0,1,0,1,0,0,1}, {1,1,0,1,0,1,0,0,1}, {1,1,0,1,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1} }; int dir[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} }; int d[9][9]; int t, sx, sy, ex, ey; int minstep = inf; void bfs() { for(int i = 0; i < 9; ++i) for(int j = 0; j < 9; ++j) d[i][j] = inf; queue<pii> Q; Q.push(make_pair(sx, sy)); d[sx][sy] = 0; while(!Q.empty()) { pii u = Q.front(); Q.pop(); if(u.first == ex && u.second == ey) break; for(int i = 0; i < 4; ++i) { int nx = u.first + dir[i][0], ny = u.second + dir[i][1]; if(nx < 0 || nx > 8 || ny < 0 || ny > 8 || maze[nx][ny] || d[nx][ny] != inf) continue; d[nx][ny] = d[u.first][u.second] + 1; Q.push(make_pair(nx, ny)); } } cout << d[ex][ey] << endl; } void dfs(int x, int y, int step) { if(x == ex && y == ey){ minstep = min(minstep, step); return; } for(int i = 0; i < 4; ++i) { int nx = x + dir[i][0], ny = y + dir[i][1]; if(nx < 0 || ny > 8 || ny < 0 || ny > 8 || maze[nx][ny]) continue; maze[nx][ny] = 1; dfs(nx, ny, step + 1); maze[nx][ny] = 0; } } int main() { for(cin >> t; t--; ) { cin >> sx >> sy >> ex >> ey; //bfs(); minstep = inf; dfs(sx, sy, 0); cout << minstep << endl; } return 0; }
相关文章推荐
- RM格式压缩电影软件 Easy RealMedia Producer Full V1.94 下载
- 在IE 浏览器中使用 jquery的fadeIn() 效果 英文字符字体加粗
- 比较简单的jquery教程 Easy Ajax with jQuery 中文版全集第1/3页
- Easy RM RMVB to DVD Burner v1.3.8 汉化版 下载 附注册码
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- Expandable "Detail" Table Rows
- linux下安装easy_install的方法
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- 归纳整理文件Easy Duplicate Finder2.24 破解版
- DM*** and Easy *** Server with ISAKMP Profiles
- easy ***
- Hadoop FS Shell
- DFS使用方法总结
- cisco packet tracer 5.3 实现基于3A的easy ***
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [Leetcode题目]19. Remove Nth Node From End of List
- [Leetcode题目]21. Merge Two Sorted Lists