Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5396af1

Browse files
authored
Merge pull request#3507 from prajval-malhotra/0139-surrounded-regions
Update 0130-surrounded-regions.cpp
2 parentsc9436c2 +139261e commit5396af1

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎cpp/0130-surrounded-regions.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,61 @@ class Solution {
5050
dfs(board, i, j +1, m, n);
5151
}
5252
};
53+
54+
/*
55+
BFS Solution
56+
*/
57+
58+
classSolution {
59+
private:
60+
int rows, cols;
61+
62+
voidbfs(int row,int col, vector<vector<char>>& board) {
63+
board[row][col] ='E';
64+
queue<pair<int,int>> q;
65+
q.push({row, col});
66+
67+
vector<pair<int,int>> directions = {{0,1}, {1,0}, {-1,0}, {0, -1}};
68+
while (!q.empty()) {
69+
auto [r, c] = q.front();
70+
q.pop();
71+
for (constauto &direction : directions) {
72+
int newRow = r + direction.first;
73+
int newCol = c + direction.second;
74+
if (newRow < rows && newRow >=0 && newCol < cols && newCol >=0 && board[newRow][newCol] =='O') {
75+
board[newRow][newCol] ='E';
76+
q.push({newRow, newCol});
77+
}
78+
}
79+
}
80+
81+
}
82+
83+
public:
84+
voidsolve(vector<vector<char>>& board) {
85+
rows = board.size();
86+
cols = board[0].size();
87+
88+
for (int row =0; row < rows; ++row) {
89+
if (board[row][0] =='O')bfs(row,0, board);
90+
if (board[row][cols -1] =='O')bfs(row, cols -1, board);
91+
}
92+
93+
for (int col =0; col < cols; ++col) {
94+
if (board[0][col] =='O')bfs(0, col, board);
95+
if (board[rows -1][col] =='O')bfs(rows -1, col, board);
96+
}
97+
98+
for (int row =0; row < rows; ++row) {
99+
for (int col =0; col < cols; ++col) {
100+
if (board[row][col] =='O') {
101+
board[row][col] ='X';
102+
}
103+
elseif (board[row][col] =='E') {
104+
board[row][col] ='O';
105+
}
106+
}
107+
}
108+
109+
}
110+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp