三种情况
岛屿数>1 则返回0岛屿数=1,只要移走一个点就能分开岛屿数=1,移除2个邻接点,就能分开(这个要仔细想,比如所有边角点只要移除另外两个邻接点,就能分开了 思路
初始算岛屿数,如果>1直接返回0遍历每个点并移除,再去算岛屿数,如果满足>2返回1最后都不满足返回2
class Solution
{
public
:
vector
<int> dx
= {1, -1, 0, 0};
vector
<int> dy
= {0, 0, 1, -1};
void dfs(int x
, int y
, vector
<vector
<int>> &grid
, vector
<vector
<int>> & vis
)
{
int n
= grid
.size();
int m
= grid
[0].size();
vis
[x
][y
] = 1;
for (int a
= 0; a
< 4; a
++)
{
int nx
= x
+ dx
[a
];
int ny
= y
+ dy
[a
];
if (nx
>= 0 and ny
>= 0 and nx
< n and ny
< m and
!vis
[nx
][ny
] and grid
[nx
][ny
])
{
dfs(nx
, ny
, grid
, vis
);
}
}
}
int count_islands(vector
<vector
<int>> & grid
)
{
int islands
= 0;
int n
= grid
.size();
int m
= grid
[0].size();
vector
<vector
<int>> vis(n
, vector
<int> (m
, 0));
for (int i
= 0; i
< n
; i
++)
{
for (int j
= 0; j
< m
; j
++)
{
if (!vis
[i
][j
] and grid
[i
][j
])
{
dfs(i
, j
, grid
, vis
);
islands
++;
}
}
}
return islands
;
}
int minDays(vector
<vector
<int>>& grid
) {
int islands
= count_islands(grid
);
int n
= grid
.size();
int m
= grid
[0].size();
if (islands
> 1 or islands
== 0)
{
return 0;
}
else
{
for (int i
= 0 ; i
< n
; i
++)
{
for (int j
= 0; j
< m
; j
++)
{
if (grid
[i
][j
])
{
grid
[i
][j
] = 0;
islands
= count_islands(grid
);
grid
[i
][j
] = 1;
if (islands
> 1 or islands
== 0)
return 1;
}
}
}
}
return 2;
}
};
转载请注明原文地址:https://tech.qufami.com/read-3663.html