POJ 3083(按规定方法遍历)

详解:http://blog.csdn.net/ac_hell/article/details/51097666

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
#define maxn 50
char mp[maxn][maxn];
int n , m;
int sx,sy;
int ex,ey;
int way[4][2] = {0,-1 , -1,0 , 0,1 , 1,0};
int vis[maxn][maxn];
struct node
{
    int x,y;
    int step;
};

bool judge(int x,int y)
{
    if( mp[x][y] == '.' && !vis[x][y] ){
        return 1;
    }
    return 0;
}

int dfs(int x,int y,int q,int kase)
{
    if( x == ex && y == ey )
        return 1;
    int res = 0;
    for(int i = q + kase ; i < q + kase + 4*(4-kase) ; i += (4-kase))
    {
        int k = i%4 ;
        int nx = x + way[k][0];
        int ny = y + way[k][1];
        if( judge(nx,ny) )
        {
            res = dfs(nx, ny, k , kase) + 1;
            break;
        }
    }
    return res;
}

int bfs()
{
    node s;
    s.x = sx;
    s.y = sy;
    s.step = 1;
    queue<node>Q;
    Q.push(s);

    while(!Q.empty())
    {
        node e = Q.front();
        Q.pop();
        if( e.x == ex && e.y == ey )return e.step;
        for(int i = 0 ; i < 4 ; ++i)
        {
            node nx = e;
            nx.x += way[i][0];
            nx.y += way[i][1];
            nx.step++;
            if( judge(nx.x,nx.y) )
            {
                Q.push(nx);
                vis[nx.x][nx.y] = 1;
            }
        }
    }
}

int main()
{
    int T;
    cin >> T;
    while( T-- )
    {
        memset(vis,0,sizeof(vis));
        cin >> m >> n;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
            {
                cin >> mp[i][j];
                if (mp[i][j] == 'S') { sx = i, sy = j; mp[i][j] = '.'; }
                if (mp[i][j] == 'E') { ex = i, ey = j; mp[i][j] = '.'; }
            }
            int q = 0 ;
            int ans1 = dfs( sx,sy,q,3 );
            int ans2 = dfs( sx,sy,q,1 );
            int ans3 = bfs();
            cout << ans1 << " " << ans2 << " " << ans3 << endl;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值