题目来源
题目描述
class Solution {
public:
int shortestBridge(vector<vector<int>>& grid) {
}
};
题目解析(待研究)
为什么是这样?????
class Solution {
// 当前来到m[i][j] , 总行数是N,总列数是M
// m[i][j]感染出去(找到这一片岛所有的1),把每一个1的坐标,放入到int[] curs队列!
// 1 (a,b) -> curs[index++] = (a * M + b)
// 1 (c,d) -> curs[index++] = (c * M + d)
// 设置距离record[a * M +b ] = 1
int infect(vector<vector<int>>& grid, int i, int j, int N, int M,
std::vector<int> &curs, int idx, std::vector<int> &record){
if (i < 0 || i == N || j < 0 || j == M || grid[i][j] != 1) {
return idx;
}
grid[i][j] = 2;
int p = i * M + j; //二维已经变成一维了, 1 (a,b) -> a * M + b
record[p] = 1;
// 收集到不同的1
curs[idx++] = p;
idx = infect(grid, i - 1, j, N, M, curs, idx, record);
idx = infect(grid, i + 1, j, N, M, curs, idx, record);
idx = infect(grid, i, j - 1, N, M, curs, idx, record);
idx = infect(grid, i, j + 1, N, M, curs, idx, record);
return idx;
}
int bfs(int N, int M, int all, int V, std::vector<int> &curs,
int size, std::vector<int> &nexts, std::vector<int> &record){
int nexti = 0; // 我要生成的下一层队列成长到哪了?
for (int i = 0; i < size; i++) {
// curs[i] -> 一个位置
int up = curs[i] < M ? -1 : curs[i] - M;
int down = curs[i] + M >= all ? -1 : curs[i] + M;
int left = curs[i] % M == 0 ? -1 : curs[i] - 1;
int right = curs[i] % M == M - 1 ? -1 : curs[i] + 1;
if (up != -1 && record[up] == 0) {
record[up] = V;
nexts[nexti++] = up;
}
if (down != -1 && record[down] == 0) {
record[down] = V;
nexts[nexti++] = down;
}
if (left != -1 && record[left] == 0) {
record[left] = V;
nexts[nexti++] = left;
}
if (right != -1 && record[right] == 0) {
record[right] = V;
nexts[nexti++] = right;
}
}
return nexti;
}
public:
int shortestBridge(vector<vector<int>>& grid) {
int N = grid.size(), M = grid[0].size();
int all = N * M;
int island = 0;
std::vector<int> curs(all, 0);
std::vector<int> nexts(all, 0);
std::vector<std::vector<int>> records(2, std::vector<int>(all, 0));
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (grid[i][j] == 1) { // 当前位置发现了1!
// 把这一片的1,都变成2,同时,抓上来了,这一片1组成的初始队列
// curs, 把这一片的1到自己的距离,都设置成1了,records
int queueSize = infect(grid, i, j, N, M, curs, 0, records[island]);
int V = 1;
while (queueSize != 0) {
V++;
// curs里面的点,上下左右,records[点]==0, nexts
queueSize = bfs(N, M, all, V, curs, queueSize, nexts, records[island]);
auto tmp = curs;
curs = nexts;
nexts = tmp;
}
island++;
}
}
}
int min = INT16_MAX;
for (int i = 0; i < all; i++) {
min = std::min(min, records[0][i] + records[1][i]);
}
return min - 3;
}
};