LeetCode 130: Surrounded Regions Solution
Master LeetCode problem 130 (Surrounded Regions), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
130. Surrounded Regions
Problem Explanation
Explanation
To solve this problem, we can perform a depth-first search (DFS) starting from the boundary cells (cells with 'O' on the edges of the board). We mark all cells connected to these boundary cells as non-surrounded regions. Then, we iterate through the board and mark any remaining 'O' cells as 'X' as they are surrounded regions.
- Time complexity: O(m * n) where m is the number of rows and n is the number of columns in the board.
- Space complexity: O(m * n) for the recursive stack space.
Solution Code
class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0) {
return;
}
int rows = board.length;
int cols = board[0].length;
for (int i = 0; i < rows; i++) {
dfs(board, i, 0);
dfs(board, i, cols - 1);
}
for (int j = 0; j < cols; j++) {
dfs(board, 0, j);
dfs(board, rows - 1, j);
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == '1') {
board[i][j] = 'O';
}
}
}
}
private void dfs(char[][] board, int i, int j) {
if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != 'O') {
return;
}
board[i][j] = '1';
dfs(board, i + 1, j);
dfs(board, i - 1, j);
dfs(board, i, j + 1);
dfs(board, i, j - 1);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 130 (Surrounded Regions)?
This page provides optimized solutions for LeetCode problem 130 (Surrounded Regions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 130 (Surrounded Regions)?
The time complexity for LeetCode 130 (Surrounded Regions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 130 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 130 in Java, C++, or Python.