|
| 1 | +class Solution(object): |
| 2 | + |
| 3 | + """ |
| 4 | + we assume 1 means unexplored, 2 is explored |
| 5 | + when we discover an unexplored place we count+=1 |
| 6 | + and use explore_adjacent() to mark the whole island to 2, so we will not count it again |
| 7 | + """ |
| 8 | + |
| 9 | + #DFS |
| 10 | + def numIslands(self, grid): |
| 11 | + if grid is None or grid==[] or grid==[[]]: return 0 |
| 12 | + |
| 13 | + count = 0 |
| 14 | + height = len(grid) |
| 15 | + width = len(grid[0]) |
| 16 | + |
| 17 | + #explore_adjacent() if grid[h][w] is unexplored, mark it as explored. 1->2. |
| 18 | + #and continue to do the same to the adjacent |
| 19 | + def explore_adjacent(h, w): |
| 20 | + #check border |
| 21 | + if h<0 or h>height-1: return |
| 22 | + if w<0 or w>width-1: return |
| 23 | + |
| 24 | + #if grid[h][w]==0: it is sea, return |
| 25 | + #if grid[h][w]==2: we already explore this place, return |
| 26 | + if grid[h][w]=='1': |
| 27 | + grid[h][w] = '2' |
| 28 | + explore_adjacent(h+1, w) |
| 29 | + explore_adjacent(h-1, w) |
| 30 | + explore_adjacent(h, w+1) |
| 31 | + explore_adjacent(h, w-1) |
| 32 | + return |
| 33 | + |
| 34 | + for h in range(height): |
| 35 | + for w in range(width): |
| 36 | + #if v==0: it is sea, continue to find unexplored |
| 37 | + #if v==2: we already explore this place, continue to find unexplored |
| 38 | + if grid[h][w]=='1': |
| 39 | + #if we discover an unexplored place |
| 40 | + #count it |
| 41 | + #and set it as root to explore the whole island |
| 42 | + count+=1 |
| 43 | + explore_adjacent(h, w) |
| 44 | + return count |
| 45 | + |
| 46 | + #BFS |
| 47 | + def numIslands(self, grid): |
| 48 | + if grid is None or grid==[] or grid==[[]]: return 0 |
| 49 | + |
| 50 | + count = 0 |
| 51 | + height = len(grid) |
| 52 | + width = len(grid[0]) |
| 53 | + |
| 54 | + def explore_adjacent(h_root, w_root): |
| 55 | + if h_root<0 or h_root>height-1: return |
| 56 | + if w_root<0 or w_root>width-1: return |
| 57 | + |
| 58 | + #start the queue from root |
| 59 | + queue = [(h_root, w_root)] |
| 60 | + |
| 61 | + while len(queue)>0: |
| 62 | + coor = queue.pop(0) |
| 63 | + h = coor[0] |
| 64 | + w = coor[1] |
| 65 | + |
| 66 | + #check border |
| 67 | + if h<0 or h>height-1: continue |
| 68 | + if w<0 or w>width-1: continue |
| 69 | + |
| 70 | + if grid[h][w]=='1': |
| 71 | + grid[h][w] = '2' |
| 72 | + queue.extend([(h+1, w), (h-1, w), (h, w+1), (h, w-1)]) |
| 73 | + |
| 74 | + #this function will end if there are no new adjacent to add to queue |
| 75 | + #which means the whole island explored (mark as 2) |
| 76 | + return |
| 77 | + |
| 78 | + for h in range(height): |
| 79 | + for w in range(width): |
| 80 | + if grid[h][w]=='1': |
| 81 | + #if we discover an unexplored place |
| 82 | + #count it |
| 83 | + #and set it as root to explore the whole island |
| 84 | + count+=1 |
| 85 | + explore_adjacent(h, w) |
| 86 | + |
| 87 | + return count |
0 commit comments