Time Complexity of No of Islands question

Viewed 117

what is the time complexity of below-written code- i think the complexity should be O(rcn) where n= maximum size island but on gfg they had written the complexity is O(V+E)

void bfs(int r, int c, vector < vector < char >> & grid) {
  queue < pair < int, int >> q;
  int row[4] = {-1,0,1,0};
  int col[4] = {0,1,0,-1};
  q.push(make_pair(r, c));
  while (!q.empty()) {
    pair < int, int > p = q.front();
    int x = p.first;
    int y = p.second;
    q.pop();

    for (int i = 0; i < 4; i++) {
      if (x + row[i] < grid.size() && y + col[i] < grid[0].size() && x + row[i] >= 0 && y + col[i] >= 0 && grid[x + row[i]][y + col[i]] == '1') {
        q.push(make_pair(x + row[i], y + col[i]));
        grid[x + row[i]][y + col[i]] = '0';
      }
    }
  }
}
int numIslands(vector < vector < char >> & grid) {
  int count = 0;
  int r = grid.size();
  if (r == 0)
    return count;
  int c = grid[0].size();
  for (int i = 0; i < r; i++) {
    for (int j = 0; j < c; j++) {
      if (grid[i][j] == '1') {
        bfs(i, j, grid);
        count++;
      }
    }
  }
  return count;
}
0 Answers
Related