ProgrammingHard

A 1000 x 1000 grid of cells must be checked for the connected component containing a start cell. Which method is correct and fast enough?

  1. A. Trying every pair of cells with nested loops, O(R^2 C^2)
  2. B. Breadth-first or depth-first search with a visited array, O(R x C) time
  3. C. Rebuilding the full grid for each step, O(R x C x R x C)
  4. D. Sorting the cells by their value, O(RC log RC) for each query

Correct answer: B. Breadth-first or depth-first search with a visited array, O(R x C) time

Each cell is visited at most once when a visited flag is set, so BFS or DFS touches each cell a constant number of times. Pair checks blow up quadratically on a large grid.

More C Programming questions

Exams that ask this topic