您的位置:首页 > 其它

FZU - 2150(双入口BFS)

2018-02-27 19:12 411 查看
反思:在数据小的时候可以用双入口的BFS来实现要求。

#include <iostream>
#include <queue>
#include <cstdio>
#include <map>
#include <cstring>
#include <stack>
#include <string>

using namespace std;

struct node
{
int x, y;
node(){}
node(int xx, int yy)
{
x = xx;
y = yy;
}
};

#define INF 0x3f3f3f3f

int n, m;
char grid[20][20];
int dis[20][20];
int dir[4][2] = {0, -1, 0, 1, -1, 0, 1, 0};

int BFS(int r1, int c1, int r2, int c2)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dis[i][j] = INF;
}
}
queue<node> q;
dis[r1][c1] = 0;
dis[r2][c2] = 0;
q.push(node(r1, c1));
q.push(node(r2, c2));
while (!q.empty()) {
node t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int tx = t.x + dir[i][0];
int ty = t.y + dir[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < m  && grid[tx][ty] == '#' && dis[tx][ty] > (dis[t.x][t.y] + 1)) {
dis[tx][ty] = (dis[t.x][t.y] + 1);
q.push(node(tx, ty));
}
}
}
int mcnt = 0;
for
4000
(int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '.') continue;
if (dis[i][j] > mcnt) {
mcnt = dis[i][j];
}
}
}
return mcnt;
}

int main()
{
int t;
cin >> t;
for (int kase = 1; kase <= t; kase++) {
cin >> n >> m;
memset (grid, '\0', sizeof(grid));
for (int i = 0; i < n; i++) {
cin >> grid[i];
}
cout << "Case " << kase << ": ";
int mcnt = INF;
for (int i1 = 0; i1 < n; i1++) {
for (int j1 = 0; j1 < m; j1++) {
if (grid[i1][j1] == '.') continue;
for (int i2 = 0; i2 < n; i2++) {
for (int j2 = 0; j2 < m; j2++) {
if (grid[i2][j2] == '.') continue;
int t = BFS (i1, j1, i2, j2);
if (t < mcnt) mcnt = t;
}
}
}
}

if (mcnt == INF) {
cout << "-1" << endl;
} else {
cout << mcnt << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: