题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
class Solution { public: /** * 判断岛屿数量 * @param grid char字符型vector<vector<>> * @return int整型 */ int solve(vector<vector<char> >& grid) { // write code here if(grid.empty()){ return 0; } int res = 0; int row = grid.size(); int col = grid[0].size(); for(int i = 0;i<row;i++){ for(int j = 0;j<col;j++){ if(grid[i][j] == '1'){ res++; dfs(grid,i,j,row,col); } } } return res; } void dfs(vector<vector<char> >&grid,int i,int j,int row,int col){ if(i<0 || i>=row || j<0 || j>= col || grid[i][j] == '0'){ return; } grid[i][j] = '0'; dfs(grid, i+1, j, row, col); dfs(grid, i, j+1, row, col); dfs(grid, i-1, j, row, col); dfs(grid, i, j-1, row, col); } };