class Solution public int visited301301=0; void dfsvectorvectorchar& grid int iint j ifi==2 && j==2 coutendl; int m=gridsize; int n=grid0size; ifi0 or i=m or j0 or j=
The code seems to have some issues with the initialization of the visited array. In C++, array sizes must be known at compile-time, so initializing the array with the size visited[301][301] is not allowed.
To fix this, you can either use dynamic memory allocation using new or use a vector to represent the visited array.
Here's an updated version of the code using a vector for the visited array:
class Solution {
public:
vector<vector<int>> visited;
void dfs(vector<vector<char>>& grid, int i, int j){
int m = grid.size();
int n = grid[0].size();
if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j] == 1 || grid[i][j] == '0') {
return;
}
visited[i][j] = 1;
dfs(grid, i+1, j);
dfs(grid, i-1, j);
dfs(grid, i, j+1);
dfs(grid, i, j-1);
}
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
int count = 0;
visited.resize(m, vector<int>(n, 0));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == '1' && visited[i][j] == 0){
dfs(grid, i, j);
count++;
}
}
}
return count;
}
};
In this updated code, the visited array is represented as a 2D vector<int>, and its size is dynamically resized to match the dimensions of the grid
原文地址: http://www.cveoy.top/t/topic/hYrb 著作权归作者所有。请勿转载和采集!