leetcode 刷题

题目一:leetcode200

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.

用一个二维数组代表一张 地图 ,这张地图由字符“0”与字符“1”组成,其中“0”字符代表 水域 ,“1”字符代表 小岛土地 ,小岛“1”被水“0”所 包围 ,当小岛土地“1”在 水平和垂直 方向相连接时,认为是同一块土地。求这张地图中小岛的 数量 。

思路:给定该二维地图grid,与一个 二维标记数组mark (初始化为0),mark数组的每个位置都与grid 对应 ,设计一个 搜索 算法,从该地图中的某个岛的 某个位置 出发, 探索 该岛的全部土地,将探索到的位置在mark数组中 标记 为1。

leetcode 刷题

算法思路(DFS):

1. 标记当前搜索位置 已被搜索 (标记当前位置的mark数组为1)。
2.按照方向数组的4个方向, 拓展 4个新位置newx、newy。
3.若新位置 不在地图范围内 ,则 忽略 。
4.如果新位置 未曾到达 过(mark[newx][newy]为0)、且 是陆地

(grid[newx][newy]为"1"), 继续DFS 该位置。

leetcode 刷题

整体思路:

求地图中 岛屿的数量 :
1.设置岛屿数量 island_num = 0;
2.设置mark数组,并 初始化 。
3.遍历 地图grid 的上所有的点,如果当前点是 陆地 ,且 未被访问 过,调用 搜索 接口
search(mark, grid, i, j);search可以是DFS或BFS; 完成 搜索后island_num++。

leetcode 刷题