U

222. Search for a Target

Hard

Problem Description

Search for a target in a two-dimensional matrix whose rows and columns are sorted.

Input Format

  • •Line 1: Two space-separated integers RR and CC (1≤R,C≤10001 \le R, C \le 1000), representing the number of rows and columns.
  • •Next RR lines: CC space-separated integers representing the grid cells.

Output Format

Print the computed integer result (e.g. number of connected components, max area, or traversal distance).

Example 1:
Input:
3 3
1 1 0
1 0 0
0 0 1
Output:
2
Explanation: Grid analysis identifies 2 distinct connected components of 1s.
Example 2:
Input:
2 2
0 0
0 0
Output:
0
Explanation: Empty grid with no active cells produces 0.
Example 3:
Input:
1 4
1 1 1 1
Output:
1
Explanation: A single contiguous row of 1s forms exactly 1 component.
Constraints:
  • 1 <= R, C <= 1000
  • 0 <= grid[i][j] <= 1
  • Time complexity target: O(R * C)
  • Auxiliary space target: O(R * C)
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online