바위타는 두루미

[leetcode] 200. Number of Islands 본문

Study/Algorithm

[leetcode] 200. Number of Islands

DoRoMii 2019. 8. 9. 13:05
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
                        

https://leetcode.com/problems/number-of-islands/

Comments