LeetCode 130
Surrounded Regions
- Problem Description:
将被‘X’围住的‘O’区域中的矩阵元素值变为‘X’,如果‘O’出现在矩阵边界则无法被‘X’包围。
具体的题目信息:
https://leetcode.com/problems/surrounded-regions/description/ - Example:
![](https://i-blog.csdnimg.cn/blog_migrate/1fa70762a51586fd90a25d2971f18795.png)
- Solution:
- 解题思路:
(1)遍历矩阵元素,遇到元素值为O
的矩阵元素将其改为X
,并保存其在矩阵中的位置
(2)从该元素向四周(左、右、上、下)遍历,如果遍历过程中出现矩阵边界元素,将标志值设为1。
(3)在一次遍历结束(即获取一块连通区域)判断标志值是否为1,若是,将记录的所有位置对应的矩阵元素值变回O
,否则保持不变。 - 编程实现:
class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size();
if (m == 0) return;
int n = board[0].size();
int flag = 0;
stack<pair<int, int>> temp;
if (m <= 2||n <= 2) return;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') {
int *p = &flag;
Flood(board, i, j, p, temp);
if (flag == 1) {
flag = 0;
while(!temp.empty()) {
board[temp.top().first][temp.top().second] = 'O';
temp.pop();
}
} else {
while(!temp.empty()) {
temp.pop();
}
}
}
}
}
}
void Flood(vector<vector<char>>& board, int i, int j, int* p, stack<pair<int, int>>& temp) {
if (i >= 0&&i < board.size()&&j >= 0&&j < board[0].size()&&board[i][j] == 'O') {
if (i == 0||i == board.size()-1||j == 0 ||j == board[0].size()-1) {
*p = 1;
}
temp.push({i, j});
board[i][j] = 'X';
Flood(board, i+1, j, p, temp);
Flood(board, i-1, j, p, temp);
Flood(board, i, j+1, p, temp);
Flood(board, i, j-1, p, temp);
}
return;
}
};