7-3 BFS应用 LC的绝地求生 (25 分)
L**C 在他小时候特别迷恋绝地求生,他就幻想着有一天能被扔到一个孤岛,他想算出整个岛屿的面积。
简化题意为一个 n∗n 的地图,共有 n∗n 个面积为 1 格子,地图左上角的格子编号为 (1,1) 右下角的格子编号为为 (n,n) 。地图上为每个格子做了标记,若编号为 (x,y) 的格子标记位 0 则代表这个区域是海,否则为陆地。
现在 L**C 空投到 (s**x,sy) 位置,他想知道他所在的岛屿的面积。
注意,可能不止一个岛屿,只用求 L**C 所在的岛屿面积。
输入格式:
第一行给出一个正整数 n(1<=n<=50) 表示地图的大小为 n∗n
第二行给出两个正整数 s**x,sy 表示 L**C 空投到的位置
之后的 n 行,每行给出 n 个整数。其中的第 i 行第 j 列的整数若为 0 则代表编号 (i,j) 位置是海洋,否则代表陆地。
保证数据一定合法,且 L**C 不会落在海里。
输出格式:
在一行中输出 L**C 所在岛屿的面积。
输入样例:
6
5 3
0 0 0 1 1 0
1 0 0 1 1 0
0 0 1 0 1 1
1 1 0 1 0 1
0 1 1 1 0 1
1 1 0 1 1 1
输出样例:
19
代码:
#include <iostream>
#include <queue>
using namespace std;
struct Node
{ //每个点
int x; //行数
int y; //列数
};
int a[101][101];
queue<Node> q;
int n, sx, sy;
int ret = 1;
void bfs()
{
int next[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
q.push(Node{sx - 1, sy - 1});
a[sx - 1][sy - 1] = 2;
while (q.size() > 0)
{
Node t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = t.x + next[i][0];
int y = t.y + next[i][1];
if (x < 0 || x > n - 1 || y < 0 || y > n - 1)
{
continue;
}
else if (a[x][y] == 1)
{
a[x][y] = 2;
ret++;
q.push({x, y});
}
}
}
cout << ret << endl;
}
int main()
{
cin >> n >> sx >> sy;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
bfs();
return 0;
}
#include <iostream>
#include <queue>
using namespace std;
struct Node
{ //每个点
int x; //行数
int y; //列数
};
int a[101][101];
int n, sx, sy;
int ret = 1;
void dfs(Node t)
{
int next[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int i = 0; i < 4; i++)
{
int x = t.x + next[i][0];
int y = t.y + next[i][1];
if (x < 0 || x > n - 1 || y < 0 || y > n - 1)
{
continue;
}
else if (a[x][y] == 1)
{
a[x][y] = 2;
ret++;
dfs(Node{x, y});
}
}
}
int main()
{
cin >> n >> sx >> sy;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
a[sx - 1][sy - 1] = 2;
dfs(Node{sx - 1, sy - 1});
cout << ret << endl;
return 0;
}