1.包围区域
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:
void solve(vector<vector<char>> &board) {
int row = board.size();
int col = board[0].size();
if(row <= 2 || col <= 2) return;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if((board[i][j] == 'O' && i == 0) || (board[i][j] == 'O' && i == row - 1))
dfs(board, i, j);
else if((board[i][j] == 'O' && j == 0) || (board[i][j] == 'O' && j == col - 1))
dfs(board, i, j);
}
}
getResult(board);
}
private:
void dfs(vector<vector<char>> &board, int Row, int Col){
if(board[Row][Col] == 'O'){
board[Row][Col] = '*';
if(Row - 1 >= 0)
dfs(board, Row - 1, Col);
if(Row + 1 <= board.size()-1)
dfs(board, Row + 1, Col);
if(Col - 1 >= 0)
dfs(board, Row, Col - 1);
if(Col + 1 < board[0].size())
dfs(board, Row, Col + 1);
}
else
return;
}
void getResult(vector<vector<char>> &board){
for(int row = 0; row < board.size(); row++)
for(int col = 0; col < board[0].size(); col++){
if(board[row][col] == '*')
board[row][col] = 'O';
else if(board[row][col] == 'O')
board[row][col] = 'X';
}
}
2.查找最大的连通面积
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int max_area = 0;
for(int i = 0; i < grid.size(); i++)
for(int j = 0; j < grid[0].size(); j++)
if(grid[i][j] == 1)max_area = max(max_area, AreaOfIsland(grid, i, j));
return max_area;
}
int AreaOfIsland(vector<vector<int>>& grid, int i, int j){
if( i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1){
grid[i][j] = 0;
return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1);
}
return 0;
}
};
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
class Solution {
public:
void contaminate(vector<vector<char> > &grid, int i, int j){
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') {
return;
}
grid[i][j]='0';
contaminate(grid, i+1, j);
contaminate(grid, i-1, j);
contaminate(grid, i, j+1);
contaminate(grid, i, j-1);
}
int numIslands(vector<vector<char>> &grid) {
int n=grid.size();
if(n==0) return 0;
int m=grid[0].size();
int cnt=0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(grid[i][j]=='1'){
cnt++;
contaminate(grid, i, j);
}
}
}
return cnt;
}
};