B. Igor and his way to work

来源:互联网 发布:java项目开发心得体会 编辑:程序博客网 时间:2024/05/16 04:34

题目链接

题意

就是给你一个1000 * 1000以内的迷宫,只能转弯两次是否能够从起点到终点。

解题思路

题意还是十分清晰的。以前没做过转弯的题目,所以花了比较久的时间。题目不能。在原来bfs的基础上修改判断重复遍历的条件。改为转弯次数是否小于前一次遍历的次数。如果大于便不用进队列了。因为上次在已经转弯的次数小于这次的情况下都没有走通,那么这次次数少的情况下走依然不会走通。

代码

    #include <iostream>    #include <stdio.h>    #include <stack>    #include <queue>    #include <string.h>    using namespace std;    const int maxn = 1005;    int stepr[4] = {1,0,-1,0};    int stepl[4] = {0,1,0,-1};    char mymap[maxn][maxn];    int visit[maxn][maxn] = {0};    struct node    {        int x,y,times;        int type;    };    queue<node> s;    bool solve(int m, int n)    {        memset(visit, 3,sizeof(visit));        int sx,sy,ex,ey;        for(int i = 0; i < m; i ++)            for(int j = 0; j < n; j++)            {                if(mymap[i][j] == 'S')                {                    sx = i;                    sy = j;                }                if(mymap[i][j] == 'T')                {                    ex = i;                    ey = j;                }            }        node temp,next;        temp.times = 0;        temp.x = sx;        temp.y = sy;        temp.type = 4;        s.push(temp);        int tx,ty;        while(!s.empty())        {            temp = s.front();            s.pop();            if(temp.times > 2)                continue;            for(int i = 0; i < 4; i++)            {                tx = temp.x + stepr[i];                ty = temp.y + stepl[i];                if(tx >= 0 && tx < m && ty >= 0 && ty < n && mymap[tx][ty] != '*' && visit[tx][ty] > temp.times)                {                    //visit[tx][ty] = 1;                    next.type = i;                    if(i != temp.type && temp.type != 4)                        next.times = temp.times+1;                    else next.times = temp.times;                    next.x = tx;                    next.y = ty;                    if(next.times > 2);                    else s.push(next);                    if(next.times > 2)                        continue;                    if(tx == ex && ty == ey)                        return true;                    visit[tx][ty] = next.times;                }            }        }        return false;    }    int main()    {        int m,n;        scanf("%d %d", &m,&n);        for(int i = 0; i < m; i++)        {            scanf("%s",mymap[i]);        }        if(solve(m,n))        {            cout << "YES" <<endl;        }        else cout << "NO" << endl;        return 0;    }
0 0
原创粉丝点击