Given an m x n 2D binary grid grid which represents a map of '1’s (land) and '0’s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
Output: 1
Example 2:
Input: grid = [
[“1”,“1”,“0”,“0”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“1”,“0”,“0”],
[“0”,“0”,“0”,“1”,“1”]
]
Output: 3
见注释
// 我的代码
class Solution {
public:
const char WATER = '0';
const char LAND = '1';
const char FOUND = 'X';
const char USED = 'O';
void floodFill(vector<vector<char>>& grid, int MAX_I, int MAX_J, int i, int j){ //递归:将发现的陆地上下左右都连成片,都标记为FOUND
if(i<0 || j<0 || i>MAX_I || j>MAX_J || grid[i][j] != LAND) return;
grid[i][j] = FOUND;
floodFill(grid, MAX_I, MAX_J, i-1, j);
floodFill(grid, MAX_I, MAX_J, i+1, j);
floodFill(grid, MAX_I, MAX_J, i, j-1);
floodFill(grid, MAX_I, MAX_J, i, j+1);
}
int numIslands(vector<vector<char>>& grid) {
if(size(grid) == 0) return 0;
int NumberOfIsland = 0;//记录岛屿数量
const int MAX_I = size(grid)-1;//就是个边界,也可省略定义,直接用size()
const int MAX_J = size(grid[0])-1;//同上
for(int i=0; i<=MAX_I; i++)
for(int j=0; j<=MAX_J; j++)
if(grid[i][j] == LAND){
floodFill(grid, MAX_I, MAX_J, i, j);
// for(int ii=0; ii<=MAX_I; ii++) //标记成FOUND会超时,想想其实也没必要标记
// for(int jj=0; jj<=MAX_J; jj++)
// if(grid[i][j] == FOUND)
// grid[i][j] = USED;
NumberOfIsland++;
}
return NumberOfIsland;
}
};
Emmmmm