sicily 无路可逃?(图的DFS)

题意:在矩阵数组中搜索两点是否可达

解法:DFS

 1 #include<iostream>
 2 #include<memory.h>
 3 using namespace std;
 4 struct position{
 5     int x;
 6     int y;
 7     position(int xx,int yy){
 8         x = xx;
 9         y = yy;
10     }
11     position(){}
12 };
13 
14 int maze[101][101];
15 int canReach;
16 position dest;    //destination
17 int row,col;
18 int direction[4][4]={{0,1},{-1,0},{0,-1},{1,0}};
19 bool visited[101][101];
20 
21 void DFS(position p){
22     if(p.x == dest.x && p.y == dest.y){
23         canReach = 1;
24         return ;
25     }
26     for(int i=0;i<4;i++){
27         int x = p.x + direction[i][0];
28         int y = p.y + direction[i][1];
29         //check  next direction whether match the destination position or not
30         if(x == dest.x && y == dest.y){
31             canReach = 1;
32             return ;
33         }
34         //satisfy the searching condition
35         if((x <=row && x >0 )&&( y <= col && y>0) && visited[x][y] == false && maze[x][y] ==1){
36             position p1 = position(x,y);
37             visited[x][y] = true;
38             DFS(p1);
39         }
40     }
41 }
42 int main(){
43     int nCase;
44     cin >> nCase;
45     while(nCase--){    
46         int beg_x,beg_y,end_x,end_y;
47         cin >> row >> col;
48         //initialization
49         canReach = 0;
50         memset(maze,-1,sizeof(maze));
51         memset(visited,false,sizeof(visited));
52         for(int i=1;i<=row;i++)
53             for(int j=1;j<=col;j++){
54                 cin >> maze[i][j];
55             }
56         cin >> beg_x >> beg_y;
57         cin >> end_x >> end_y;
58         position p = position(beg_x,beg_y);
59         dest = position(end_x,end_y);
60         visited[beg_x][beg_y] = true;
61         //depth-first search
62         DFS(p);
63 
64         if(canReach){
65             cout<<1<<endl;
66         }else{
67             cout<<0<<endl;
68         }
69     }
70 }

 

posted @ 2014-01-10 15:40  shaoshuai1990  阅读(290)  评论(0编辑  收藏  举报