Skip to content

Commit 8726bce

Browse files
committedFeb 2, 2025
Add solution #130
1 parent aadb495 commit 8726bce

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@
134134
127|[Word Ladder](./0127-word-ladder.js)|Hard|
135135
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
136136
129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium|
137+
130|[Surrounded Regions](./0130-surrounded-regions.js)|Medium|
137138
131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium|
138139
133|[Clone Graph](./0133-clone-graph.js)|Medium|
139140
134|[Gas Station](./0134-gas-station.js)|Medium|

‎solutions/0130-surrounded-regions.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 130. Surrounded Regions
3+
* https://leetcode.com/problems/surrounded-regions/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n matrix board containing letters 'X' and 'O', capture regions
7+
* that are surrounded:
8+
* - Connect: A cell is connected to adjacent cells horizontally or vertically.
9+
* - Region: To form a region connect every 'O' cell.
10+
* - Surround: The region is surrounded with 'X' cells if you can connect the region with
11+
* 'X' cells and none of the region cells are on the edge of the board.
12+
*
13+
* To capture a surrounded region, replace all 'O's with 'X's in-place within the original
14+
* board. You do not need to return anything.
15+
*/
16+
17+
/**
18+
* @param {character[][]} board
19+
* @return {void} Do not return anything, modify board in-place instead.
20+
*/
21+
var solve = function(board) {
22+
for (let i = 0; i < board.length; i++) {
23+
for (let j = 0; j < board[0].length; j++) {
24+
if (board[i][j] === 'O'
25+
&& (!i || !j || i === board.length - 1 || j === board[0].length - 1)) {
26+
dfs(i, j);
27+
}
28+
}
29+
}
30+
31+
for (let i = 0; i < board.length; i++) {
32+
for (let j = 0; j < board[0].length; j++) {
33+
if (board[i][j] === '-') {
34+
board[i][j] = 'O';
35+
} else {
36+
board[i][j] = 'X';
37+
}
38+
}
39+
}
40+
41+
function dfs(i, j) {
42+
if (i < 0 || i >= board.length || j < 0 || j >= board[i].length
43+
|| board[i][j] === '-' || board[i][j] === 'X') {
44+
return;
45+
}
46+
47+
board[i][j] = '-';
48+
dfs(i - 1, j);
49+
dfs(i + 1, j);
50+
dfs(i, j - 1);
51+
dfs(i, j + 1);
52+
}
53+
};

0 commit comments

Comments
 (0)
Please sign in to comment.