题目:
给你一个大小为 n x n 的二元矩阵 grid ,其中 1 表示陆地,0 表示水域。
岛 是由四面相连的 1 形成的一个最大组,即不会与非组内的任何其他 1 相连。grid 中 恰好存在两座岛 。
你可以将任意数量的 0 变为 1 ,以使两座岛连接起来,变成 一座岛 。
返回必须翻转的 0 的最小数目。
示例 1:
输入:grid = [[0,1],[1,0]]
输出:1
示例 2:
输入:grid = [[0,1,0],[0,0,0],[0,0,1]]
输出:2
示例 3:
输入:grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
输出:1
提示:
n == grid.length == grid[i].length
2 <= n <= 100
grid[i][j] 为 0 或 1
grid 中恰有两个岛
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shortest-bridge
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
先找到两个岛: 使用深度优先的方式
从一个岛去找到另外一个岛的最短距离: 使用广度优先的搜索方式
代码:
class Solution {
public:
int shortestBridge(vector<vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
int** group = new int*[rows];
for(int i = 0;i<rows;i++)
{
group[i] = new int[cols];
memset(group[i],0,sizeof(int)*cols);
}
int dires[5] = {1,0,-1,0,1};
int id = 0;
for(int i = 0;i<rows;i++)
{
for(int j = 0;j<cols;j++)
{
if(grid[i][j] == 1 && group[i][j] == 0)
{
stack<int> s;
s.push(i*cols + j);
id++;
group[i][j] = id;
while(!s.empty())
{
int curr = s.top();
s.pop();
int x = curr / cols;
int y = curr % cols;
for(int m = 0;m<4;m++)
{
int nextX = x + dires[m];
int nextY = y + dires[m+1];
if(nextX >= 0 && nextX < rows && nextY >= 0 && nextY < cols && grid[nextX][nextY] == 1 && group[nextX][nextY] == 0)
{
group[nextX][nextY] = id;
s.push(nextX * cols + nextY);
}
}
}
}
}
}
unordered_set<int> targets;
queue<pair<int,int>> q;
for(int i = 0;i < rows;i++)
{
for(int j = 0;j < cols;j++)
{
if(group[i][j] == 1)
q.emplace(i,j);
else if(group[i][j] == 2)
targets.insert(i * cols + j);
}
}
int depth = 0;
while(!q.empty())
{
for(int i = q.size() - 1;i >= 0;i--)
{
int x = q.front().first;
int y = q.front().second;
q.pop();
if(targets.find(x * cols + y) == targets.end())
{
for(int i = 0;i < 4;i++)
{
int nextX = x + dires[i];
int nextY = y + dires[i+1];
if (nextX >= 0 && nextX < rows && nextY >= 0 && nextY < cols && group[nextX][nextY] != 1)
{
group[nextX][nextY] = 1;
q.emplace(nextX,nextY);
}
}
}
else
return depth - 1;
}
depth++;
}
return -1;
}
};