俄罗斯怎么小,为什么北约怎么怕?
原来这是俄罗斯的一块飞地。并不是俄罗斯所有的领土。
给你一个大小为 m x n 的二进制矩阵 grid ,其中 0 表示一个海洋单元格、1 表示一个陆地单元格。
一次 移动 是指从一个陆地单元格走到另一个相邻(上、下、左、右)的陆地单元格或跨过 grid 的边界。
返回网格中 无法 在任意次数的移动中离开网格边界的陆地单元格的数量。
这是一道常规的bfs搜索题,显而易见从四个边界入手,grid【】【】为1就入队,然后在用广搜,如果与边界相连接格子的值为1,就把grid改为0,之后再遍历一下,看有几个1。
class Solution {
public:
int room[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int numEnclaves(vector<vector<int>>& grid) {
int x = grid.size(), y = grid[0].size();
if (x == 1)return 0;
queue<pair<int, int>>q;
for (int i = 0; i < y; i++)//四周边界入队1
if (grid[0][i] == 1)
q.emplace(0, i);
for (int i = 0; i < y; i++)
if (grid[x - 1][i] == 1)
q.emplace(x-1, i);
for (int i = 0; i < x; i++)
if (grid[i][y-1] == 1)
q.emplace(i, y-1);
for (int i = 0; i < x; i++)
if (grid[i][0] == 1)
q.emplace(i, 0);
while (!q.empty()) {//bfs搜素
int first_x = q.front().first;
int first_y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {//first元素的四周搜素
int next_x = first_x + room[i][0];
int next_y = first_y + room[i][1];
if (next_x >= 0 && next_x < x && next_y >= 0 && next_y < y && grid[next_x][next_y] == 1) {
q.emplace(next_x, next_y);
grid[next_x][next_y] = 0;
}
}
}
int k = 0;
for (int i = 1; i < x-1; i++)
for (int j = 1; j < y-1; j++)
if (grid[i][j] == 1)
k++;
return k;
}
};
我也写了好多bfs和dfs的题目了,总结一下这类图表题目的思路:
1.明确用什么,bfs还是dfs;
2.我们要搜索的第一个点(起始点)是什么;
3.我们怎么来判断这个点我们是否搜索过;
4.根据题目要求给出答案了。
jsl