岛屿的数量
class Solution {
public:
vector<vector<char>> grid;
int x[4] = {-1, 0, 1, 0}, y[4] = {0, 1, 0, -1};
int numIslands(vector<vector<char>>& grid_) {
grid = grid_;
int m = grid.size(), n = grid[0].size();
if(!m) return 0;
int cnt = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (grid[i][j]=='1'){
dfs(i, j);
cnt++;
}
}
}
return cnt;
}
void dfs(int i, int j, int &minx, int &miny, int &maxx, int &maxy){
grid[i][j]=0;
for (int k = 0; k < 4; k++){
int a = i + x[k], b = j + y[k];
if (a>=0&&a<grid.size()&&b>=0&&b<grid[0].size()&&grid[a][b]=='1'){
dfs(a, b);
}
}
}
};
每个岛屿的最小boundingbox
class Solution {
public:
vector<vector<char>> grid;
int x[4] = {-1, 0, 1, 0}, y[4] = {0, 1, 0, -1};
int numIslands(vector<vector<char>>& grid_) {
grid = grid_;
int m = grid.size(), n = grid[0].size();
if(!m) return 0;
int cnt = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (grid[i][j]=='1'){
int minx = i, miny = j;
int maxx = i, maxy = j;
dfs(i, j, minx, miny, maxx, maxy);
cout << minx <<" "<< miny <<" "<< maxx <<" "<< maxy <<endl;
cnt++;
}
}
}
return cnt;
}
void dfs(int i, int j, int &minx, int &miny, int &maxx, int &maxy){
grid[i][j]=0;
for (int k = 0; k < 4; k++){
int a = i + x[k], b = j + y[k];
if (a>=0&&a<grid.size()&&b>=0&&b<grid[0].size()&&grid[a][b]=='1'){
minx = min(minx, a);
maxy = max(maxy, b);
maxx = max(maxx, a);
miny = min(miny, b);
dfs(a, b, minx, miny, maxx, maxy);
}
}
}
};
floodfill
一、实现4向flood fill算法。给定:
- 一幅单通道灰度图像img;
- 一个起始点坐标x,y;
- 一个目标颜色color;
从(x,y)位置起,将连通区域内所有像素颜色赋值为color。连通区域定义:上下相邻,或左右相邻,且颜色相同的像素,属于同一连通区域。
int x[x] = {-1, 0, 1, 0}, y[4] = {0, 1, 0, -1};
int floodfill(int x, int y, vector<vector<int>> img){
dfs(x, y, img);
}
void dfs(int i, int j, vector<vector<int>>img){
img[i][j] = color;
for(int k = 0; k < 4; k++){
int a = i+x[k], b = j+y[k];
if(a>=0&&a<img.size()&&b>=0&&b<=img[0].size()&&img[a][b]=img[i][j]){
dfs(int i, int j, vector<vector<int> > img);
}
}
}