九度oj 题目1335:闯迷宫

http://ac.jobdu.com/problem.php?id=1335

View Code
 1 /*宽度搜索,注意对于宽度搜索树中 ,第几层的记录,
2 层数即是最短步数*/
3 #include<iostream>
4 #include<cstdio>
5 #include<queue>
6 using namespace std;
7 class node
8 {
9 public: node(int x1,int y1,int deep1)
10 {
11 x=x1;
12 y=y1;
13 deep=deep1;
14 }
15 int x,y,deep;
16 };
17 int mat[108][108];
18 int dir[6][3];
19 int n;
20 void init()
21 {
22 dir[1][0]=-1;dir[1][1]=0;//
23 dir[2][0]=0;dir[2][1]=1;//
24 dir[3][0]=1;dir[3][1]=0;//
25 dir[4][0]=0;dir[4][1]=-1;//
26 }
27 void bfs()
28 {
29 queue<node>q;
30 q.push(node(0,0,-1));
31 mat[0][0]=1;
32 int step=-1;
33 int x,y,deep,i;
34 while(!q.empty())
35 {
36 node mynode=q.front();
37 q.pop();
38
39 x=mynode.x;
40 y=mynode.y;
41 deep=mynode.deep+1;
42 if(x==n-1 && y==n-1)
43 {
44 step=deep;
45 break;
46 }
47 for(i=1;i<=4;i++)//宽度搜索
48 {
49 x=mynode.x+dir[i][0];
50 y=mynode.y+dir[i][1];
51 if((x>-1&&x<n) && (y>-1&&y<n) && mat[x][y]==0)
52 {
53 q.push(node(x,y,deep));
54 mat[x][y]=1;///表示走过了
55 }
56 }
57 //cout<<"***************************"<<endl;
58 }
59 printf("%d\n",step);//cout<<step<<endl;
60
61 }
62 int main()
63 {
64 init();
65 while(scanf("%d",&n)==1)
66 {
67 int i,j;
68 for(i=0;i<n;i++)
69 {
70 for(j=0;j<n;j++) scanf("%d",&mat[i][j]);//cin>>mat[i][j];
71 }
72 if(mat[0][0]==1 || mat[n-1][n-1]==1)
73 {
74 printf("-1\n");//cout<<"-1"<<endl;
75 continue;
76 }
77 bfs();
78 }
79 return 0;
80 }


 

posted @ 2012-03-28 19:47  keepmoving89  阅读(360)  评论(0编辑  收藏  举报