POJ-3009
来源:互联网 发布:表白网php源码 编辑:程序博客网 时间:2024/06/05 17:46
其实第一次看到这道题目,我会下意识的想用BFS去解,因为BFS适合于求解最短路问题。但是对于这道题目是不适合的,因为每走一步棋盘的状态都是会改变的,然后再结合题目中要求的必须在10步之内完成这个任务,于是想到用DFS去求解这个问题。其中我觉得——if(step >= best) 剪枝比较重要;然后就是if(nx >= h || nx < 0 || ny >= w || ny < 0 || board[nx][ny] == 1)中的board[nx][ny] == 1的情况必须判断,这一点很容易被忽视掉;最后就是要注意使用dfs()之后不要忘了将棋盘还原。
#include<iostream>#define MAX 30using namespace std;int w, h, best;int ex, ey;int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};int board[MAX][MAX];void dfs(int sx, int sy, int step);int main(){ int sx, sy; while(cin>>w>>h){ if(w==0 && h == 0) break; for(int i = 0; i < h; i++) for(int j= 0; j < w; j++) cin>>board[i][j];//输入棋盘的数据 for(int i = 0; i < h; i++) for(int j = 0; j < w; j++){ if(board[i][j] == 2){sx = i; sy = j;} if(board[i][j] == 3){ex = i; ey = j;}//记录起点和终点的坐标 } best = 12; dfs(sx, sy, 0); if(best <= 10) cout<<best<<endl; else cout<<"-1"<<endl; } return 0;}void dfs(int sx, int sy, int step){ if(step >= best) return; //如果步数已经大于或等于之前算出的最小步数,则退出 for(int i = 0; i < 4; i++){ int nx = sx + dx[i]; int ny = sy + dy[i]; if(nx >= h || nx < 0 || ny >= w || ny < 0 || board[nx][ny] == 1) continue;//如果越界,或者第一步就是block,则无法往下走 while(nx < h && nx >= 0 && ny < w && ny >= 0 && board[nx][ny] != 1){//在允许行走的范围内,一直往下走 if(nx == ex && ny == ey){//如果已经走到了终点,则比较步数 if(step + 1 < best) best = step + 1; break; } nx += dx[i]; ny += dy[i]; }//退出循环的条件有三个:1.越界了,2.撞上block了,3.已经走到终点了 if(nx == ex && ny == ey) continue;//如果走到终点 if(nx >= 0 && nx < h && ny >= 0 && ny < w && board[nx][ny] == 1){//如果撞上了block board[nx][ny] = 0; dfs(nx-dx[i], ny-dy[i], step+1); board[nx][ny] = 1; } }}
0 0
- POJ 3009
- poj 3009
- POJ 3009
- POJ 3009
- POJ-3009
- POJ 3009
- POJ 3009
- poj-3009
- poj--3009
- poj 3009
- POJ 3009
- poj-3009
- poj 3009
- POJ 3009
- poj 3009
- 【POJ】3009
- POJ 3009
- poj 3009
- Football (aka Soccer) -uva10194 模拟题
- JSP中动态INCLUDE与静态INCLUDE的区别
- 30 查看当前Linux系统中安装的shell及其版本
- 惹恼程序员的十件事
- Android完全退出多个activity程序
- POJ-3009
- 【史上最坑爹的游戏】002 关卡选择画面的实现
- Error 1962: No operating system found.
- IE6浏览器退役留下22%市场空白,正待分食
- Java实现定时任务的三种方法
- var endindex = 1
- 每日一C之C语言const用法
- Spring事务配置的五种方式
- 微软的平板电脑Surface