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?
- A. Trying every pair of cells with nested loops, O(R^2 C^2)
- B. Breadth-first or depth-first search with a visited array, O(R x C) time
- C. Rebuilding the full grid for each step, O(R x C x R x C)
- 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
- int a[3][3] = {{2,7,6},{9,5,1},{4,3,8}}; Are all of the row sums, column sums and both diagonal sums equal to 15?
- Row-major storage of int a[4][5] means a[i][j] is at flat index i 5 + j. What flat index holds a[3][2]?
- int a[2][3] with a pointer p = &a[0][0]. Which expression gives the number of elements between a[0][0] and a[1][2]?
- The sum of the elements of a[i][j] = i j over the 4 x 4 matrix equals what?
- Which statement about matrix multiplication in C is correct for an m x k matrix times a k x n matrix?
- Sum of a 2 x 2 window of m[i][j] = i + j starting at (1,1) in a 4 x 4 grid, i.e. m[1][1] + m[1][2] + m[2][1] + m[2][2]. What is the value?