Surrounded Regions

Graphs Traversal Problems Medium
  • This problem is essentially a variation of the often-used 'Flood Fill' algorithm, which is an important tool in computer graphics
  • Applications such as Photoshop make use of this algorithm in their "fill" tool, where an entire area of similar color is replaced by another color with just one click
  • Similarly, this problem replaces an entire area of similar characters with another character
  • Besides, Flood Fill algorithm is also applied in gaming industry for mechanics like territory control, path finding, and more

Given a matrix mat of size N x M where every element is either ‘O’ or ‘X’. Replace all ‘O’ with ‘X’ that is surrounded by ‘X’. An ‘O’ (or a set of ‘O’) is considered to be surrounded by ‘X’ if there are ‘X’ at locations just below, above, left, and right of it.

Examples:

Input: mat = [ ["X", "X", "X", "X"], ["X", "O", "O", "X"], ["X", "X", "O", "X"], ["X", "O", "X", "X"] ]

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

Explanation:

The 'O' cells at positions (1,1), (1,2), (2,2), and (3,1) are surrounded by 'X' cells in all directions (horizontally and vertically).

However, the 'O' region at (3,1) is adjacent to an edge of the board, so it cannot be completely surrounded by 'X' cells. Therefore, it remains unchanged.

Input: mat = [ ["X", "X", "X"], ["X", "O", "X"], ["X", "X", "X"] ]

Output: [ ["X", "X", "X"], ["X", "X", "X"], ["X", "X", "X"] ]

Explanation: The only 'O' cell at position (1,1) is completely surrounded by 'X' cells in all directions (horizontally and vertically). Hence, it is replaced with 'X' in the output.

Input: mat = [ ["X", "X", "X", "O"], ["X", "X", "X", "X"], ["O", "X", "X", "X"], ["X", "X", "X", "X"] ]

Constraints

  •   N == mat.length
  •   M == mat[i].length
  •   1 <= N, M <= 300
  •   mat[i][j] is 'X' or 'O'.

Hints

  • Start from all 'O's on the boundary (first & last row, first & last column). Use DFS or BFS to mark all connected 'O's as safe (e.g., change them to -1 temporarily).
  • "Traverse the grid again: Convert remaining 'O's to 'X' (they are enclosed). Convert marked -1 back to 'O'."

Company Tags

Rakuten Cerner Robinhood Texas Instruments Ubisoft Oracle Snowflake JPMorgan Chase Morgan Stanley Dropbox Chewy Etsy Nutanix Reddit Splunk Swiggy Salesforce Unity Technologies Epic Games Boston Consulting Group Airbnb Cloudflare Bungie Instacart Activision Blizzard Google Microsoft Amazon Meta Apple Netflix Adobe