赞
踩
(题目略改),POJ那题数据太弱!!!
问题描述:
定义一个二维数组 N*M (其中 2<=N<=10;2<=M<=10 ),如 5×5 数组下所示:Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
输入描述:5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
(0,0) (1,0) (2,0) (2,1) (2,2) (2,3) (2,4) (3,4) (4,4)
题解:
广搜+记录路径
AC代码:
- #include<iostream>
- #include<cstdio>
- #include<algorithm>
- using namespace std;
- int map[10][10];
- int vis[10][10];
- int n,m;
- int head,rear;
- //四个方向
- int dx[4]={0,1,-1,0};
- int dy[4]={1,0,0,-1};
- struct node{
- int x;
- int y;
- int pre;
- }num[1100];
- void print(int n)
- {
-
- if(num[n].pre != -1){
- print(num[n].pre);
- printf("(%d,%d) ",num[n].x,num[n].y);
- }
- }
- void bfs(){
- head=0;
- rear=0;
- num[rear].x=0,num[rear].y=0,num[rear++].pre=-1;
- while(head<rear){
- for(int i=0;i<4;i++){ //四个方向搜搜搜
- int bj1=num[head].x+dx[i];
- int bj2=num[head].y+dy[i];
- if(bj1>=n||bj2>=m||bj1<0||bj2<0||map[bj1][bj2]==1)
- continue;
- map[bj1][bj2]=1;
- num[rear].x=bj1;
- num[rear].y=bj2;
- num[rear].pre=head;
- rear++;
- if(bj1==n-1&&bj2==m-1) //到达终点
- print(head);
-
- }
- head++;
- }
- }
- int main()
- {
-
- cin>>n>>m;
- for(int i=0;i<n;i++){
- for(int j=0;j<m;j++){
- scanf("%d",&map[i][j]);
- }
- }
- printf("(0,0) ");
- bfs();
- printf("(%d,%d) ",n-1,m-1);
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。