Advertisement
Singasking

Untitled

Jun 22nd, 2023
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int numIslands(vector<vector<char>>& grid) {
  4. int N = grid.size();
  5. int M = grid[0].size();
  6. vector<vector<int>> visited(N, vector<int>(M, 0));
  7. queue<pair<int,int>> q;
  8. int count = 0;
  9.  
  10. for (int r = 0; r < N; r++) {
  11. for(int c = 0; c < M; c++) {
  12. if(grid[r][c] == '1' && visited[r][c] == 0) {
  13. count++;
  14. q.push({r, c});
  15.  
  16. while(!q.empty()) {
  17. pair<int,int> temp = q.front();
  18. q.pop();
  19. int rn = temp.first;
  20. int cn = temp.second;
  21. visited[rn][cn] = 1;
  22.  
  23. vector<pair<int,int>> directions = {{rn+1,cn}, {rn,cn+1}, {rn-1,cn}, {rn,cn-1}};
  24.  
  25. for (auto t : directions) {
  26. int rn = t.first;
  27. int cn = t.second;
  28.  
  29. if(rn >= 0 && rn < N && cn >= 0 && cn < M && grid[rn][cn] == '1' && visited[rn][cn] == 0) {
  30. q.push({rn, cn});
  31. }
  32. }
  33. }
  34. }
  35. }
  36. }
  37. return count;
  38. }
  39. };
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement