130. Surrounded Regions
题目描述
Given a 2D board containing ‘X’ and ‘O’ (the letter 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:
void solve(vector<vector<char>>& board) {
int m = board.size(), n = m?board[0].size():0, indy = m-1, indx = n-1;
if(!m) return;
bool closure = true; queue<pair<int, int>> que;
vector<vector<int>> query(m, vector<int>(n,0));
for(int row = 0; row < m; row++) {
for(int col = 0; col < n; col++) {
queue<pair<int, int>> tmp;
if(board[row][col] == 'O' && !query[row][col]) {
closure = true;
query[row][col] = 1; board[row][col] = 'X';
tmp.push(make_pair(row, col)); que.push(make_pair(row, col));
while(!tmp.empty()) {
int r = tmp.front().first, c = tmp.front().second;
tmp.pop();
if(r == 0 || r == indy || c == 0 || c == indx) closure = false;
if(r - 1 >= 0) {
if(board[r-1][c] == 'O') {
board[r-1][c] = 'X'; query[r-1][c] = 1;
que.push(make_pair(r-1, c)); tmp.push(make_pair(r-1, c));
}
}
if(c - 1 >= 0) {
if(board[r][c-1] == 'O') {
board[r][c-1] = 'X'; query[r][c-1] = 1;
que.push(make_pair(r, c-1)); tmp.push(make_pair(r, c-1));
}
}
if(r + 1 <= indy) {
if(board[r+1][c] == 'O') {
board[r+1][c] = 'X'; query[r+1][c] = 1;
que.push(make_pair(r+1, c)); tmp.push(make_pair(r+1, c));
}
}
if(c + 1 <= indx) {
if(board[r][c+1] == 'O') {
board[r][c+1] = 'X'; query[r][c+1] = 1;
que.push(make_pair(r, c+1)); tmp.push(make_pair(r, c+1));
}
}
}
// recover initial state
if(!closure) {
while(!que.empty()) {
int r = que.front().first, c = que.front().second;
que.pop();
board[r][c] = 'O';
}
}
while(!que.empty()) que.pop();
}
}
}
}
};
73. Set Matrix Zeroes
题目描述
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
如果某一项是0,那么该行或者列就都会变成0。
代码实现
class Solution {
public:
void setZeroes(vector<vector<int>>& mat) {
int m = mat.size(), n = m?mat[0].size():0;
vector<int> rec(m+n, 0);
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(!mat[i][j]) { rec[i] = 1; rec[m+j] = 1; }
for(int i = 0; i < m; i++) {
if(rec[i] == 1) {
for(int j = 0; j < n; j++) mat[i][j] = 0;
}
}
for(int i = m; i < m+n; i++) {
if(rec[i] == 1) {
for(int j = 0; j < m; j++) mat[j][i-m] = 0;
}
}
}
};