两道题应该分别是我在蓝桥杯和南大夏令营遇到的原题,比较相似
200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
解:遍历所有的位置进行DFS寻找区域,走过的位置标记为2,防止重复计算区域
代码:
class Solution {
public:
int numIslands(vector<vector<char> >& grid) {
int row = grid.size();
if (row == 0) return 0;
int col = grid[0].size();
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1') {
DFS(grid, i, j);
count++;
}
}
}
return count;
}
void DFS(vector<vector<char> >& grid, int x, int y) {
int row = grid.size();
int col = grid[0].size();
grid[x][y] = '2';
if (x+1 < row && grid[x+1][y] == '1') DFS(grid, x+1, y);
if (y+1 < col && grid[x][y+1] == '1') DFS(grid, x, y+1);
if (x-1 >= 0 && grid[x-1][y] == '1') DFS(grid, x-1, y);
if (y-1 >= 0 && grid[x][y-1] == '1') DFS(grid, x, y-1);
}
};
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.
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
解:此题和上题的区别是边界不能包围区域,所以在DFS时碰到边界时就不能形成区域了,于是在DFS时先将走过的位置标记为1,之后一旦遇到边界,就将走过的位置的标记改成2以防止重复走,如果成功找到区域换成'X'即可。
代码:
class Solution {
public:
void solve(vector<vector<char> >& board) {
int row = board.size();
if (row == 0) return;
int col = board[0].size();
bool temp = true;
for (int i = 1; i < row-1; i++) {
for (int j = 1; j < col-1; j++) {
if (board[i][j] == 'O') {
temp = DFS(board, i, j);
if (temp == true) {
for (int k = 0; k < row; k++) {
for (int t = 0; t < col; t++) {
if (board[k][t] == '1') board[k][t] = 'X';
}
}
} else {
for (int k = 0; k < row; k++) {
for (int t = 0; t < col; t++) {
if (board[k][t] == '1') board[k][t] = '2';
}
}
}
}
}
}
for (int k = 0; k < row; k++) {
for (int t = 0; t < col; t++) {
if (board[k][t] == '2') board[k][t] = 'O';
}
}
}
bool DFS(vector<vector<char> >& board, int x, int y) {
int row = board.size();
int col = board[0].size();
board[x][y] = '1';
if (x == row-1 || x == 0 || y == col-1 || y == 0) return false;
bool res = true;
if (board[x+1][y] == 'O') res &= DFS(board, x+1, y);
if (board[x-1][y] == 'O') res &= DFS(board, x-1, y);
if (board[x][y-1] == 'O') res &= DFS(board, x, y-1);
if (board[x][y+1] == 'O') res &= DFS(board, x, y+1);
return res;
}
};
本文介绍了解决两个经典图遍历问题的方法:计算二维网格中岛屿的数量及围攻被‘X’包围的所有‘O’区域。通过深度优先搜索(DFS)策略,有效地解决了这两类问题,并详细阐述了代码实现。
1526

被折叠的 条评论
为什么被折叠?



