题目:
Given an m x n
2d grid
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
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
is'0'
or'1'
.
代码:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.size() < 1)
return 0;
int h = grid.size();
int w = grid[0].size();
if(w < 1)
return 0;
int count = 0;
vector<vector<int>> record(h, vector<int>(w, 0));
vector<vector<int>> d = {{1,0}, {-1, 0}, {0, 1}, {0,-1}};
for(int i = 0; i<h; i++)
{
for(int j = 0; j<w; j++)
{
if(grid[i][j] == '1' && !record[i][j])
{
count++;
queue<pair<int, int>> q;
q.push(pair<int, int>(i, j));
while(!q.empty())
{
pair<int, int> cur = q.front();
q.pop();
record[cur.first][cur.second] = 1;
pair<int, int> pos;
for(int k = 0; k<4; k++)
{
pos.first = cur.first + d[k][0];
pos.second = cur.second + d[k][1];
if(pos.first < 0 || pos.first >= h || pos.second < 0 || pos.second >= w)
continue;
if(!record[pos.first][pos.second] && grid[pos.first][pos.second] == '1')
q.push(pos);
record[pos.first][pos.second] = 1;
}
}
}
}
}
return count;
}
};
效率优于99.81%~