北大 acm 3009
2013-09-05 14:07
274 查看
#include<iostream> using namespace std; const int N=25; char maze ; int w,h; int count; void dfs(int x,int y,int step) { if (step>count) //如果当前的步数超过了最小的步数,停止 return; int i; for(i=x+1;i<h;i++) //往下走 { if (i==x+1 && maze[i][y]=='1') break; if (maze[i][y]=='3') //保证获取最小的步数 { if(step<count) count=step; } if (maze[i][y]=='1') { maze[i][y]='0'; dfs(i-1,y,step+1); maze[i][y]='1'; break; } } for(i=x-1;i>=0;i--) //往上走 { if (i==x-1 && maze[i][y]=='1') break; if (maze[i][y]=='3') { if(step<count) count=step; } if (maze[i][y]=='1') { maze[i][y]='0'; dfs(i+1,y,step+1); maze[i][y]='1'; break; } } for(i=y-1;i>=0;i--) //往左走 { if (i==y-1 && maze[x][i]=='1') break; if (maze[x][i]=='3') { if(step<count) count=step; } if (maze[x][i]=='1') { maze[x][i]='0'; dfs(x,i+1,step+1); maze[x][i]='1'; break; } } for(i=y+1;i<w;i++) //往右走 { if (i==y+1 && maze[x][i]=='1') break; if (maze[x][i]=='3') { if(step<count) count=step; } if (maze[x][i]=='1') { maze[x][i]='0'; dfs(x,i-1,step+1); maze[x][i]='1'; break; } } } int main() { int i,j,x,y; while (cin>>w>>h) { count=11; if (w==0&&h==0) break; for (i=0;i<h;i++) { for (j=0;j<w;j++) { cin>>maze[i][j]; if (maze[i][j]=='2') { x=i; y=j; } } } dfs(x,y,1); if (count>10) cout<<"-1"<<endl; else cout<<count<<endl; } return 0; }
上面的代码分别编写了上下左右四个方向,可以合并起来考虑,用一个二维数组表示四个方向,代码长度可以缩短许多。
#include<iostream> #include <cstring> using namespace std; const int N=25; char maze ; int dir[4][2]={{1,0},{0,-1},{-1,0},{0,1}}; int w,h; int count; void dfs(int x,int y,int step) { if (step>count) return; for (int i=0;i<4;i++) { int tmpx=x+dir[i][0]; int tmpy=y + dir[i][1]; if(maze[tmpx][tmpy]=='1') continue; while (1) { if (tmpx<0||tmpx==h ||tmpy<0 || tmpy==w) break; else { if (maze[tmpx][tmpy]=='3') { if (step<count) count=step; return; } if (maze[tmpx][tmpy]=='1') { maze[tmpx][tmpy]='0'; dfs(tmpx-dir[i][0],tmpy-dir[i][1],step+1); maze[tmpx][tmpy]='1'; break; } } tmpx+=dir[i][0]; tmpy+=dir[i][1]; } } } int main() { int i,j,x,y; while (cin>>w>>h) { count=11; if (w==0&&h==0) break; for (i=0;i<h;i++) { for (j=0;j<w;j++) { cin>>maze[i][j]; if (maze[i][j]=='2') { x=i; y=j; } } } dfs(x,y,1); if (count>10) cout<<"-1"<<endl; else cout<<count<<endl; } return 0; }
相关文章推荐
- 北大acm题目分类
- 北大ACM2991——Crane~~线段树
- 北大ACM推荐题目
- 北大ACM1006——Biorhythms~~中国剩余定理
- 北大ACM暑期培训感想
- 北大计算机研究生的ACM感言
- 北大ACM1127——Jack Straws
- 北大ACM暑期培训课程目录
- 北大ACM之路
- 北大ACM试题分类
- 北大ACM试题分类
- 北大ACM 1004 Financial Management
- 北大ACM 2262 Goldbach's Conjecture
- 北大ACM-题型分类的代码
- 北大ACM2139——Six Degrees of Cowvin Bacon
- 北大ACM1258——Agri-Net~~最小生成树
- ACM之北大——1000_A+B Problem
- 北大ACM1067——取石子游戏
- 北大ACM分类
- 北大ACM题目分类