十五月明


私信TA

用户名:dotcpp0605328

访问量:2835

签 名:

等  级
排  名 500
经  验 4457
参赛次数 0
文章发表 68
年  龄 18
在职情况 学生
学  校 曲阜师范大学
专  业 人工智能

  自我简介:

Easy

解题思路:

注意事项:

参考代码:

#include <iostream>

#include <cstring>

#include <queue>

using namespace std;

struct node

{

    int x, y;

}t;

queue <node> q;

int dx[] = {0, 0, -1, 1};           //位移方向

int dy[] = {-1, 1, 0, 0};

int main()

{

    bool a[105][105];   //0为未走过,1为走过或者障碍

    int T;

    cin>>T;

    while(T--)

    {

        int m, n;

        cin>>m>>n;          //行 列

        memset(a, 0, sizeof(a));

        

        int x0, y0, x1, y1;

        char temp;

        for (int i = 1; i <= m; i++)

        {

            for (int j = 1; j <= n; j++)

            {

                cin >> temp;

                if (temp == 'S') x0 = i, y0 = j;

                if (temp == 'E') x1 = i, y1 = j;

                if (temp == '#') a[i][j] = 1;

            }

        }    

        

        

        //开始广度优先遍历咯

        int s = 0;          //计算步数


        a[x0][y0] = 1;

        q.push(node({x0, y0}));         //起点入队

        

        bool flag = 1;      //用以区分是队空还是找到终点,退出循环的

        while (!q.empty() && flag)         //寻找是队空还是找到终点

        {

            s++;

            int size = q.size();

            for (int i = 1; i <= size; i++)

            {

                t = q.front();          //取队头

                q.pop();                //删队头

                

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

                {

                    int x = t.x + dx[j];

                    int y = t.y + dy[j];

                    if (x >= 1 && x <= m && y >= 1 && y <= n && a[x][y] == 0)

                    {

                        a[x][y] = 1;

                        if (x == x1 && y == y1) flag = 0;          //到终点了

                        else q.push(node({x, y}));              //新点入队

                    }

                }

            }

        }

        if (!flag) cout<<s<<endl;

        else cout<<-1<<endl;

    }

    return 0;

}


 

0.0分

1 人评分

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

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区