https://leetcode.com/problems/number-of-islands/description/
思路还是很直接的吧,每个位置做BFS, BFS访问整个棋盘 n*m仅仅一次, 两重循环n*m,所有总的时间复杂度还是n*m
int xx[4] = {0, 0, -1, 1};
int yy[4] = {1, -1, 0, 0};
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.size() == 0) return 0;
int visit[grid.size()][grid[0].size()] ;
memset(visit, 0, sizeof(visit));
int ans = 0 ;
for (int i = 0; i < grid.size(); i ++) {
for (int j = 0; j < grid[0].size(); j++) {
if (!visit[i][j] && grid[i][j] == '1') {
ans ++;
visit[i][j] = 1;
queue< pair<int, int> > q;
q.push( make_pair(i, j) );
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int k = 0; k < 4; k++) {
int px = x + xx[k];
int py = y + yy[k];
// cout << "ok" << px << " y:" << py << endl;
if (px >= 0 && px < grid.size() && py >= 0 && py < grid[0].size() && !visit[px][py] && grid[px][py] == '1') {
// cout << "-->ok" << px << " y:" << py << endl;
visit[px][py] = 1;
q.push( make_pair(px, py) );
}
}
}
}
}
}
return ans;
}
};