Leetcode 130: Surrounded Regions

grid47
grid47
Exploring patterns and algorithms
Oct 25, 2024 7 min read

A grid of cells gently surrounded by a calming border of light, with certain areas being 'captured.
Solution to LeetCode 130: Surrounded Regions Problem

You are given an m x n matrix board containing letters ‘X’ and ‘O’. Capture all regions that are surrounded by ‘X’. A region is captured if it is surrounded by ‘X’ cells and cannot reach the edges of the board.
Problem
Approach
Steps
Complexity
Input: The input is an m x n matrix containing 'X' and 'O'. Each element represents a cell of the board.
Example: [['X','X','X','X'], ['X','O','O','X'], ['X','X','O','X'], ['X','O','X','X']]
Constraints:
• 1 <= m, n <= 200
• board[i][j] is either 'X' or 'O'.
Output: The output is a matrix where all 'O' regions that are surrounded by 'X' cells are captured by replacing 'O' with 'X'.
Example: [['X','X','X','X'], ['X','X','X','X'], ['X','X','X','X'], ['X','O','X','X']]
Constraints:
• The output will be a modified version of the input board with captured 'O' regions.
Goal: The goal is to capture the regions of 'O' surrounded by 'X'.
Steps:
• 1. Traverse the entire board to identify 'O' cells on the borders (edges).
• 2. Use a depth-first search (DFS) to mark the 'O' cells connected to the borders as safe.
• 3. After the traversal, replace all remaining 'O' cells (surrounded regions) with 'X'.
• 4. Restore all 'O' cells marked as safe back to 'O'.
Goal: The board will always have at least 1 row and 1 column.
Steps:
• 1 <= m, n <= 200
• board[i][j] is 'X' or 'O'.
Assumptions:
• The input will always be a valid matrix where m and n are within the specified constraints.
Input: [['X','X','X','X'], ['X','O','O','X'], ['X','X','O','X'], ['X','O','X','X']]
Explanation: In this case, 'O's that are surrounded by 'X's (not touching the edge) are captured and turned into 'X's.

Input: [['X']]
Explanation: This board has no 'O's, so no cells are captured and the board remains unchanged.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus