poj 2312 Battle City

poj 2312 Battle City
http://acm.pku.edu.cn/JudgeOnline/problem?id=2312
poj 2312 Battle City
简单的BFS





Source Code

Problem: 2312 User: lovecanon
Memory: 1244K Time: 16MS
Language: GCC Result: Accepted

#include < stdio.h >
typedef 
struct  node 
{
    
int  x;
    
int  y;
}node;
node Q[
100000 ];
char  board[ 301 ][ 301 ];
int  step[ 301 ][ 301 ];
int  m,n;
const   int  dx[] = { 0 , 0 , - 1 , 1 },dy[] = { - 1 , 1 , 0 , 0 };

int  ok( int  x, int  y)
{
    
if (x >= 0 && x < m && y >= 0 && y < n)  return   1 ;
    
else   return   0 ;
}

void  solve( int  x1, int  y1, int  x2, int  y2)
{
    
int  i,j,cntx,cnty,nextx,nexty,head,tail,tmp,minstep = 0x7fffffff ;
    cntx
= x1;cnty = y1;head = tail = 0 ;
    
for (i = 0 ;i < m;i ++ )
        
for (j = 0 ;j < n;j ++ )
            step[i][j]
= 0x7fffffff ;
    step[cntx][cnty]
= 0 ;

    
while ( 1 )
    {
        
for (i = 0 ;i < 4 ;i ++ )
        {
            nextx
= cntx + dx[i];
            nexty
= cnty + dy[i];
            
if (ok(nextx,nexty))
            {
                
if (board[nextx][nexty] == ' E ' )
                {
                    tmp
= step[cntx][cnty] + 1 ;
                    
if (tmp < step[nextx][nexty])
                    {
                        step[nextx][nexty]
= tmp;
                        Q[
++ tail].x = nextx;
                        Q[tail].y
= nexty;
                    }
                }
                
if (board[nextx][nexty] == ' B ' )
                {
                    tmp
= step[cntx][cnty] + 2 ;
                    
if (tmp < step[nextx][nexty])
                    {
                        step[nextx][nexty]
= tmp;
                        Q[
++ tail].x = nextx;
                        Q[tail].y
= nexty;
                    }
                }
                
if (board[nextx][nexty] == ' T ' )
                {
                    
if (step[cntx][cnty] + 1 < minstep)  minstep = step[cntx][cnty] + 1 ;
                }
            }
        }
        
if (head == tail)   break ;
        
else
        {
            cntx
= Q[ ++ head].x;
            cnty
= Q[head].y;
        }
 
    }
    
if (minstep == 0x7fffffff )  printf( " -1\n " );
    
else  printf( " %d\n " ,minstep);

}

int  main()
{
    
while ( 1 )
    {
        
int  i,j;
        
int  x1,y1,x2,y2;

        scanf(
" %d%d " , & m, & n);
        getchar();

        
if (m == 0 && n == 0 return   0 ;

        
for (i = 0 ;i < m;i ++ )
        {
            
for (j = 0 ;j < n;j ++ )
            {
                board[i][j]
= getchar();
                
if (board[i][j] == ' Y ' )
                {
                    x1
= i;y1 = j;
                }
                
if (board[i][j] == ' T ' )
                {
                    x2
= i;y2 = j;
                }
            }
            getchar();
        }
        solve(x1,y1,x2,y2);
    }
    
return   0 ;

}

你可能感兴趣的:(poj 2312 Battle City)