本文主要是介绍LeetCode *** 130. Surrounded Regions,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given a 2D board containing 'X'
and 'O'
, capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
For example,
X X X X X O O X X X O X X O X X
After running your function, the board should be:
X X X X X X X X X X X X X O X X
分析:
代码:
class Solution {
public:int m, n;void solve(vector<vector<char>>& board) {m = board.size();if (m == 0 || m == 1)return;n = board[0].size();if (n == 1)return;queue<pair<int, int>> record;for (int j = 0; j<n; ++j) {if (board[0][j] == 'O')record.push(pair<int, int>(0, j));if (board[m - 1][j] == 'O')record.push(pair<int, int>(m - 1, j));}for (int i = 0; i<m; ++i) {if (board[i][0] == 'O')record.push(pair<int, int>(i, 0));if (board[i][n - 1] == 'O')record.push(pair<int, int>(i, n - 1));}while (!record.empty()) {pair<int, int> tmp = record.front();record.pop();int i = tmp.first, j = tmp.second;board[tmp.first][tmp.second] = 'T';if (i>0 && board[i - 1][j] == 'O')record.push(pair<int,int>(i - 1, j));if (i<m - 1 && board[i + 1][j] == 'O')record.push(pair<int,int>(i + 1, j));if (j>0 && board[i][j - 1] == 'O')record.push(pair<int,int>(i, j - 1));if (j<n - 1 && board[i][j + 1] == 'O')record.push(pair<int,int>(i, j + 1));}for (int i = 0; i<m; ++i)for (int j = 0; j<n; ++j)if (board[i][j] == 'O')board[i][j] = 'X';else if (board[i][j] == 'T')board[i][j] = 'O';}
};
这篇关于LeetCode *** 130. Surrounded Regions的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!