HDU 2579 Dating with girls(2) BFS

/*
---------------------------------------------
    Time : 14:45-15:25 2012.2.13
    Stratege : BFS (KeyPoint:定义一个三维数组,num[x][y][z] ;
                x, y用于存放当前所在的迷宫坐标,z用于存放所走过的
                时间和题目中K的模数。因为x, y可以反复走,所以需要
                多开一维数组,进行更新状态
    ACMer :JohnsondDu
    
    Problem : 2579 ( Dating with girls(2) )     Judge Status : Accepted
    RunId : 5111908    Language : C++    Author : a312745658
-----------------------------------------------
*/

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <memory.h>
#include <queue>
#include <algorithm>
using namespace std ;

#define INF 0xfffffff
struct Node
{
    int x, y ;
    int step ;
}n, m ;
int direct[4][2] = {1, 0, 0, -1, -1, 0, 0, 1} ;
char map[105][105] ;
bool flag ;
int num[105][105][11] ;
int R, C, K ;
int sx, sy, dx, dy ;
int tcase ;

int main()
{
    int i, j, k ;
    cin >> tcase ;
    while (tcase --)
    {
        cin >> R >> C >> K ;
        for (i = 0; i < R; i ++)
            for (j = 0; j < C ; j++)
            {
                cin >> map[i][j] ;
                if (map[i][j] == 'Y')
                    sx = i, sy = j ;
                if (map[i][j] == 'G')
                    dx = i, dy = j ;
            }
        for (i = 0; i < R; i ++)
            for (j = 0; j < C; j ++)
                for (k = 0; k < 11; k ++)
                    num[i][j][k] = INF ;     //初始化步数为最大,以更新状态
        flag = false ;

        n.x = sx ;
        n.y = sy ;
        n.step = 0 ;

        queue <Node> Q ;
        Q.push (n) ;

        while (! Q.empty())
        {
            m = Q.front () ;
            Q.pop() ;

            if (m.x == dx && m.y == dy)
            {
                flag = true ;
                break ;
            }
            //cout << "(" << m.x << "," << m.y << ")" << endl ;
            for (i = 0; i < 4; i ++)
            {
                n.x = m.x + direct[i][0] ;
                n.y = m.y + direct[i][1] ;
                n.step = m.step + 1 ;

                if (n.x >= 0 && n.y >= 0 && n.x < R && n.y < C )
                {
                    if (map[n.x][n.y] == '#' && n.step % K != 0) //若n.step % K == 0,石头会消失,可走
                        continue ;
                    if (num[n.x][n.y][n.step%K] <= n.step)       //更新步数。
                        continue ;
                    num[n.x][n.y][n.step%K] = n.step ;
                    Q.push (n) ;
                }
            }
        }
        if (flag)
            printf ("%d\n", m.step) ;
        else
            printf ("Please give me another chance!\n") ;

    }
    return 0 ;
}

你可能感兴趣的:(HDU 2579 Dating with girls(2) BFS)