1 """ 2 Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance. 3 The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|. 4 If no land or water exists in the grid, return -1. 5 Example 1: 6 Input: [[1,0,1],[0,0,0],[1,0,1]] 7 Output: 2 8 Explanation: 9 The cell (1, 1) is as far as possible from all the land with distance 2. 10 Example 2: 11 Input: [[1,0,0],[0,0,0],[0,0,0]] 12 Output: 4 13 Explanation: 14 The cell (2, 2) is as far as possible from all the land with distance 4. 15 """ 16 """ 17 BFS的方法 18 先找到grid中所有的1的位置,保存在queue中,若全是1或者没有1,返回-1 19 从这些1所在的位置开始进行广度优先搜索,即搜索四个方向, 20 如果搜索的位置上的值为0,保存这些坐标, 21 作为下一次搜索的起点,并将这些位置的值设置为1,以免重复搜索。 22 这样每扩散一层,计数器加1,直到没有可搜索的起点,返回计数器的值就为最远的距离 23 """ 24 class Solution: 25 def maxDistance(self, grid): 26 row, col = len(grid), len(grid[0]) #求出地图的行列 27 queue = [] #保存地图中出现'1'的位置 28 for i in range(row): #遍历地图。将为'1'的所有位置放入队列 29 for j in range(col): 30 if grid[i][j] == 1: 31 queue.append((i, j)) 32 if len(queue) == row*col or not queue: #如果地图全为'1'或者全为'0',返回-1 33 return -1 34 level = 0 #记录每次扩张的距离 35 while queue: 36 newqueue = [] #记录每层扩张 37 for x, y in queue: 38 for i, j in [[x-1, y], [x+1, y], [x, y-1], [x, y+1]]: #每层扩张的四个方向 39 if 0 <= i <row and 0<= j < col and grid[i][j] == 0: 40 newqueue.append((i, j)) #如果为0,搜索到了,保存位置放入队列,下一轮搜索 41 grid[i][j] = 1 #并将搜索过的位置 变为1 42 queue = newqueue 43 level += 1 44 return (level-1)