HDOJ1242(Rescue) bfs

一起来救天使了!

 

#include <iostream>
#include 
<queue>
using namespace std;

const int MAX_SIZE = 202
;

typedef 
struct

{
    
int
 x, y;
    
int cc;//花费时间

}
Node;

int dir[4][2= {{-1,0},{1,0},{0,-1},{0,1}}
;

int
 cost[MAX_SIZE][MAX_SIZE];
char
 graph[MAX_SIZE][MAX_SIZE];
int
 m, n;
int sx, sy,//起点

    dx, dy;//终点

void init()
{
    
for(int i = 0; i < m; i++
)
        
for(int j = 0; j < n; j++
)
        
{
            
if(graph[i][j] == 'r'
)
            
{sx = i; sy = j;}

            
if(graph[i][j] == 'a')
            
{dx = i; dy = j;}

            cost[i][j] 
= -1;
        }

}


bool isBound(int x, int y)
{
    
if(x < 0 || y < 0
)
        
return false
;
    
if(x >= m || y >=
 n)
        
return false
;
    
return true
;
}


void bfs()
{
    Node a,b;
    
int
 i;
    queue
<Node>
 Q;
    
//----------------------------


    a.x 
= sx;
    a.y 
=
 sy;
    a.cc 
= 0
;
    cost[a.x][a.y] 
= 0
;

    
//----------------------------

    Q.push(a);
    
while(!
Q.empty())
    
{
        a 
=
 Q.front();
        Q.pop();
        
for(i = 0; i < 4; i++
)
        
{
            b.x 
= a.x + dir[i][0
];
            b.y 
= a.y + dir[i][1
];
            b.cc 
= a.cc + 1
;
            
if(graph[b.x][b.y] == '#'|| !
isBound(b.x, b.y))
                
continue
;
            
if(graph[b.x][b.y] == 'x'
)
                b.cc
++;//砍死卫兵加时间

            if(cost[b.x][b.y] == -1 || b.cc < cost[b.x][b.y])
            
{
                Q.push(b);
                cost[b.x][b.y] 
=
 b.cc;
            }

        }

    }

}


int main()
{
    
int
 i;
    
while(cin>>m>>
n)
    
{
        
for(i = 0; i < m; i++
)
            cin
>>
graph[i];
        init();
        bfs();
        
if(cost[dx][dy] == -1
)
            cout
<<"Poor ANGEL has to stay in the prison all his life."<<
endl;
        
else

            cout
<<cost[dx][dy]<<endl;
    }

    
return 0;
}

posted on 2009-03-24 08:26  Xredman  阅读(1097)  评论(0编辑  收藏  举报

导航