兜兜里有糖


私信TA

用户名:zz2267860734

访问量:337

签 名:

等  级
排  名 963
经  验 3278
参赛次数 3
文章发表 1
年  龄 21
在职情况 学生
学  校 郑州科技学院
专  业 计算机科学与技术

  自我简介:

TA的其他文章

解题思路;广度优先搜索    广度优先搜索具有最短路性

注意事项:    搜索完T时注意 恢复标记     

参考代码:  新手  代码写的有点乱



#include<iostream>

#include<algorithm>

#include<queue>

using namespace std;


 typedef long long ll;

const int N = 210;

char g[N][N];

int n, m;

bool v[N][N],c[N][N];

bool k;

struct node

{

    int x, y,d;

    

};

int x, y;

int d[4][2] = { {-1,0}, {0,-1}, {1,0}, {0,1} };

bool pd(int x,int y)

{

    return x >= 0 && x < n&& y >= 0 && y < m;

}

int bfs1(int x, int y)

{

    queue<node> q;

    q.push({ x,y,0 });

    v[x][y] = true;

    while (!q.empty())

    {

        node now = q.front();

        q.pop();


        for (int i = 0; i < 4; i++)

        {

            int dx = now.x + d[i][0];

            int dy = now.y + d[i][1];


            if (pd(dx, dy) && !v[dx][dy] && g[dx][dy] != '1')

            {


                if (g[dx][dy] == 'T')

                {

                    

                    return now.d + 1;

                }

                else

                {

                    v[dx][dy] = true;

                    q.push({ dx,dy,now.d + 1 });

                }

            }

        }

    }

}

int bfs2(int x,int y)

{

    queue<node> q;

    q.push({x,y,0});

    c[x][y] = true;

    while (!q.empty())

    {

        node now = q.front();

        q.pop();

        

        for (int i = 0; i < 4; i++)

        {

            int dx = now.x + d[i][0];

            int dy = now.y + d[i][1];


            if (pd(dx, dy) && !c[dx][dy] && g[dx][dy] != '1')

            {

            

                if (g[dx][dy] == 'E')

                {

                    return now.d + 1;

                }

                else

                {

                    c[dx][dy] = true;

                    q.push({dx,dy,now.d+1});

                }

            }

        }

    }

}

int main()

{

    cin >> n >> m;


    for (int i = 0; i < n; i++)

        for (int j = 0; j < m; j++)

            cin >> g[i][j];

    for (int i = 0; i < n; i++)

        for (int j = 0; j < m; j++)

        {

            if (g[i][j] == 'S')

            {

                x = i; y = j;

                break;

            }

        }int f = bfs1(x, y) ;

    for (int i = 0; i < n; i++)

        for (int j = 0; j < m; j++)

        {

            if (g[i][j] == 'T')

            {

                x = i; y = j;

                break;

            }

        }


    int r=bfs2(x,y);

    cout << f+r << endl;;


    return 0;

}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区