码迷,mamicode.com
首页 > 其他好文 > 详细

HDU_2579_bfs

时间:2016-09-15 22:53:09      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

http://acm.split.hdu.edu.cn/showproblem.php?pid=2579

 

简单bfs题,刚开始在纠结怎么存放vis,因为步数可能有几百步,这么多格子开数组的话也太多了,后来想到只要保存步数%k的状态就好了,bfs到达该点的步数肯定是最优的。

 

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

string s[105];
int r,c,k,dir[4][2] = {-1,0,0,-1,1,0,0,1},vis[105][105][15],flag;

struct point
{
    int x,y,counts;
}start;

int main()
{
    int n;
    cin >> n;
    while(n--)
    {
        flag = 0;
        memset(vis,0,sizeof(vis));
        cin >> r >> c >> k;
        for(int i = 0;i < r;i++)   cin >> s[i];
        for(int i = 0;i < r;i++)
        {
            for(int j = 0;j < c;j++)
            {
                if(s[i][j] == Y)
                {
                    start.x = i;
                    start.y = j;
                    goto there;
                }
            }
        }
        there:
        start.counts = 0;
        queue<point> q;
        q.push(start);
        vis[start.x][start.y][0] = 1;
        while(!q.empty())
        {
            int x = q.front().x,y = q.front().y,counts = q.front().counts;
            q.pop();
            if(s[x][y] == G)
            {
                flag = 1;
                cout << counts << endl;
                break;
            }
            for(int i = 0;i < 4;i++)
            {
                int xx = x+dir[i][0],yy = y+dir[i][1],z = (counts+1)%k;
                if(xx < 0 || xx >= r || yy < 0 || yy >= c)  continue;
                if(s[xx][yy] == # && z)  continue;
                if(vis[xx][yy][z])  continue;
                point temp;
                temp.x = xx;
                temp.y = yy;
                temp.counts = counts+1;
                q.push(temp);
                vis[xx][yy][z] = 1;
            }
        }
        if(!flag)   cout << "Please give me another chance!" << endl;
    }
    return 0;
}

 

HDU_2579_bfs

标签:

原文地址:http://www.cnblogs.com/zhurb/p/5875528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!