力扣200. 岛屿数量

 

记录一下自己的思路,典型的dfs题目

题目:【https://leetcode.cn/problems/number-of-islands/description/?envType=study-plan-v2&envId=top-interview-150

 

 1 class Solution {
 2 public:
 3     void body(vector<vector<char>>& grid, int x, int y)
 4     {
 5         if (x < 0 || x >= grid[0].size() || y < 0 || y >= grid.size() || '1' != grid[y][x])
 6             return ;
 7 
 8         grid[y][x] = '2';
 9         body(grid, x + 1, y);
10         body(grid, x, y + 1);
11         body(grid, x - 1, y);
12         body(grid, x, y - 1);
13     }
14     int numIslands(vector<vector<char>>& grid) {
15         int count = 0;
16         for (int i = 0; i < grid.size(); ++i) {
17             for (int j = 0; j < grid[0].size(); ++j) {
18                 if ('1' == grid[i][j]) {
19                     body(grid, j, i);
20                     count++;
21                 }
22             }
23         }
24         return count;
25     }
26 };

 

posted @ 2025-04-14 11:26  J&YANG  阅读(17)  评论(0)    收藏  举报