森渊


私信TA

用户名:senyuan

访问量:592

签 名:

等  级
排  名 28380
经  验 494
参赛次数 0
文章发表 3
年  龄 0
在职情况 学生
学  校 杭州市风帆中学
专  业

  自我简介:

解题思路:很明显,这是一道最最基础的广度优先搜索,废话不多说,上代码

注意事项:注意“size = q.size()"

参考代码:

#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];

int T;

scanf("%d", &T);

for (int i = 1; i <= T; i++){

int m, n;

scanf("%d%d", &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;

bool b = 1;

a[x0][y0] = 1;

q.push(node({x0, y0}));

while (!q.empty() && b){

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], 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) b = 0;

else q.push(node({x, y}));

}

}

}

}

if (!b) printf("%d\n", s);

else printf("-1\n");

}

return 0;

}



 

0.0分

1 人评分

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

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区