Leetcode 力扣 岛屿问题 C++实现
Leetcode 力扣 岛屿问题 C++实现 写在最开始 问题描述 解决办法 代码 写在最开始 第一次尝试写博客,不知道能不能坚持下去,尝试记录一些学习的过程。 已经大三了才开始写,感觉有点晚了,希望以后也可以慢慢写,哈哈。 问题描述 题目:给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 解决办法 这里需要用到BFS,一开始想了一会,后来发现只需要一个递归就可以解决问题,有的人用到了一个同样维度的visit表来标记是否访问,但是其实只要把探索过的 ‘1’ 全部置为 ‘0’ ,起到的效果与visit表相同。 注意需要加上错误检测,因为有的用例是空的,而且row的检测还要在col之前,否则访问空的col会报错。 代码 下面是完整的代码,比较简单,也不存在读不懂的问题。 class Solution { public: int numIslands(vector<vector<char>>& grid) { int row = grid.size(); if(row==0) return 0; int col = grid[0].size(); if(col==0) return 0; int count=0; int i,j; for(i=0;i<row