leetcode------Number of Islands
标题: | Number of Islands |
通过率: | 22.8% |
难度: | 中等 |
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.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
继续是python代码
今天发现python一个知识就是python字符串中不支持修改某个字符,
例子:a="1234"
错误操作a[1]="3"
正确操作a=a[:1]+"3"+a[2:]
那么本题就是一个深度搜索,但是题目下面的tags说还可以广度搜索,我刚开始是想的广度搜索,感觉很麻烦,要维护一个位置表,
深度搜索就是遍历所有节点,然后想四个方向都遍历,一直走到四个方向全部为0时,则一块陆地诞生,同时每次遍历时要把走过的路径置0操作,否则在遍历整个列表的时候会出现重复的操作,
代码如下:
1 class Solution: 2 tmp=[] 3 # @param grid, a list of list of characters 4 # @return an integer 5 def numIslands(self, grid): 6 count,self.tmp=0,grid 7 for i in range(len(self.tmp)): 8 for j in range(len(self.tmp[0])): 9 if grid[i][j]=='1': 10 self.dfs(i,j) 11 count+=1 12 return count 13 14 15 def dfs(self,x,y): 16 if x< 0 or x>=len(self.tmp) or y<0 or y>= len(self.tmp[0]): return 17 if self.tmp[x][y]!='1':return 18 self.tmp[x]=self.tmp[x][:y]+"0"+self.tmp[x][y+1:] 19 self.dfs(x+1,y) 20 self.dfs(x-1,y) 21 self.dfs(x,y+1) 22 self.dfs(x,y-1) 23