1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { vector<vector<int>> visited; public: int numIslands(vector<vector<char>>& grid) { if(grid.empty()) return 0; if(grid[0].empty()) return 0; int islandNum = 0; visited = vector<vector<int>>(grid.size(), vector<int>(grid[0].size(), false)); for(int i = 0; i < grid.size(); i++){ for(int j = 0; j < grid[0].size(); j++){ if(grid[i][j] == '1' && !visited[i][j]) { BFS(grid, i, j); ++islandNum; } } } return islandNum; } void BFS(vector<vector<char>> &g, int x, int y){ visited[x][y] = true; g[x][y] = '0'; queue<pair<int, int>> BFS; BFS.push(pair<int, int>(x, y)); while(!BFS.empty()){ pair<int, int> pos = BFS.front(); int curX = pos.first, curY = pos.second; if(curX - 1 >= 0 && g[curX - 1][curY] == '1' && !visited[curX - 1][curY]){ BFS.push(pair<int, int>(curX - 1, curY)); visited[curX - 1][curY] = true; } if(curX + 1 < g.size() && g[curX + 1][curY] == '1' && !visited[curX + 1][curY]){ BFS.push(pair<int, int>(curX + 1, curY)); visited[curX + 1][curY] = true; } if(curY - 1 >= 0 && g[curX][curY - 1] == '1' && !visited[curX][curY - 1]){ BFS.push(pair<int, int>(curX, curY - 1)); visited[curX][curY - 1] = true; } if(curY + 1 < g[0].size() && g[curX][curY + 1] == '1' && !visited[curX][curY + 1]){ BFS.push(pair<int, int>(curX, curY + 1)); visited[curX][curY + 1] = true; } BFS.pop(); } } };
|