바위타는 두루미
[leetcode] 200. Number of Islands 본문
728x90
200. Number of Islands
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:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
BFS 또는 DFS로 풀면 되는 문제
BFS로 풀었다.
class Solution(object):
def numIslands(self, grid):
cnt_land = 0
q = []
d = [[-1,0,1,0],[0,-1,0,1]]
len_y = len(grid)
if len_y ==0 :
return 0
len_x = len(grid[0])
if len_x == 0:
return 0
for i in range(len_y):
for j in range(len_x):
if grid[i][j] == "1":
grid[i][j] = "-1"
q.append((i,j))
while q :
cur = q.pop(0)
for k in range(4):
next_y = cur[0]+d[0][k]
next_x = cur[1]+d[1][k]
if next_y >= 0 and next_y <len_y and next_x >=0 and next_x <len_x and grid[next_y][next_x] == "1":
grid[next_y][next_x] ="-1"
q.append((next_y, next_x))
cnt_land +=1
return cnt_land
'Study > Algorithm' 카테고리의 다른 글
[leetcode]22. Generate Parentheses (0) | 2019.08.09 |
---|---|
[leetcode]17. Letter Combinations of a Phone Number (0) | 2019.08.09 |
[leetcode]230. Kth Smallest Element in a BST (0) | 2019.08.09 |
[leetcode]116. Populating Next Right Pointers in Each Node (0) | 2019.08.09 |
[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2019.08.09 |
Comments