/130. Surrounded Regions

130. Surrounded Regions

Medium
Arrays44.9% acceptance

Given a 2D list grid of size m x n containing only the characters X and O, modify grid in-place such that all regions of O cells that are completely surrounded by X cells (i.e., not connected to any edge of the grid) are replaced with X. Cells are connected horizontally and vertically. Do not return anything; modify grid directly.

Example 1

Input: [[O,O,X,X],[X,O,O,X],[X,X,O,X],[O,X,X,O]]

Output: [[O,O,X,X],[X,X,X,X],[X,X,X,X],[O,X,X,O]]

Explanation: Only the middle region of Os is surrounded and replaced.

Example 2

Input: [[O,X],[X,O]]

Output: [[O,X],[X,O]]

Explanation: No surrounded region; no change.

Example 3

Input: [[X,O,X],[O,O,O],[X,O,X]]

Output: [[X,O,X],[O,O,O],[X,O,X]]

Explanation: All Os touch the edge; no surrounded region.

Constraints

  • 1 <= len(grid) <= 200
  • 1 <= len(grid[0]) <= 200
  • grid[i][j] in {X, O} for all 0 <= i < len(grid), 0 <= j < len(grid[0])
Python (current runtime)

Case 1

Input: [['X','O','X','O'],['O','O','X','X'],['X','X','O','X'],['O','X','X','O']]

Expected: [['X','O','X','O'],['O','O','X','X'],['X','X','O','X'],['O','X','X','O']]

Case 2

Input: [['X','X','X'],['X','O','X'],['X','X','X']]

Expected: [['X','X','X'],['X','X','X'],['X','X','X']]

Case 3

Input: [['O','O','O'],['O','X','O'],['O','O','O']]

Expected: [['O','O','O'],['O','X','O'],['O','O','O']]

Case 4

Input: [['X','X','X','X'],['X','O','O','X'],['X','O','O','X'],['X','X','X','X']]

Expected: [['X','X','X','X'],['X','X','X','X'],['X','X','X','X'],['X','X','X','X']]