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 49 50 51 52 53 54 55 56
| class Solution { public: void dfs(vector<vector<char>>& grid,vector<vector<bool>>& visited,int x, int y) { if (visited[x][y]) return; visited[x][y] = true; pair<int, int> neigbors[4]{pair<int, int>(x, y + 1),pair<int, int>(x + 1, y),pair<int, int>(x, y - 1),pair<int, int>(x - 1, y)}; for (pair<int, int>& item : neigbors) { if (item.first < 0 || item.first >= grid.size() || item.second < 0 || item.second >= grid[0].size()) continue; if (grid[item.first][item.second] == '0') continue; if (visited[item.first][item.second]) continue; dfs(grid, visited,item.first, item.second); } } void bfs(vector<vector<char>>& grid,vector<vector<bool>>& visited,int x, int y) { queue<pair<int, int>> queue; queue.push(pair<int, int>(x,y)); while(!queue.empty()) { auto item = queue.front();queue.pop(); int x = item.first,y = item.second; if(visited[x][y]) continue; visited[x][y] = true; pair<int, int> neigbors[4]{pair<int, int>(x, y + 1),pair<int, int>(x + 1, y),pair<int, int>(x, y - 1),pair<int, int>(x - 1, y)}; for (pair<int, int>& item : neigbors) { if (item.first < 0 || item.first >= grid.size() || item.second < 0 || item.second >= grid[0].size()) continue; if (visited[item.first][item.second]) continue; if (grid[item.first][item.second] == '0') continue; queue.push(item); } } } int numIslands(vector<vector<char>>& grid) { int cnt = 0; vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size(),false)); for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if(!visited[i][j] && grid[i][j] == '1') { bfs(grid,visited,i,j); cnt++; } } } return cnt; } };
|