Skip to content

Commit 3c129f1

Browse files
committed
[BOJ] number-of-islands (Medium)
1 parent c51b5e6 commit 3c129f1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

김지호/4주차/260120.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# https://leetcode.com/problems/number-of-islands
2+
3+
from typing import List
4+
from collections import deque
5+
6+
class Solution:
7+
def numIslands(self, grid: List[List[str]]) -> int:
8+
N = len(grid)
9+
M = len(grid[0])
10+
11+
12+
visited = [[False] * M for _ in range(N)]
13+
14+
count = 0
15+
for row in range(N):
16+
for col in range(M):
17+
if(visited[row][col] == False and grid[row][col] == '1') :
18+
count += 1
19+
self.BFS(grid,row,col,visited,N,M)
20+
return count
21+
22+
def BFS(self,grid,row,col,visited,N,M):
23+
drow = [1,0,-1,0]
24+
dcol = [0,-1,0,1]
25+
26+
queue = deque()
27+
queue.append([row,col])
28+
visited[row][col] = True
29+
30+
while(len(queue) != 0):
31+
row, col = queue.popleft()
32+
for i in range(4):
33+
nrow = row + drow[i]
34+
ncol = col + dcol[i]
35+
if(0 <= nrow < N and 0 <= ncol < M and visited[nrow][ncol] == False and grid[nrow][ncol]=='1'):
36+
queue.append([nrow,ncol])
37+
visited[nrow][ncol] = True
38+
39+
40+
41+
answer = Solution()
42+
print(answer.numIslands([
43+
["1","1","1","1","0"],
44+
["1","1","0","1","0"],
45+
["1","1","0","0","0"],
46+
["0","0","0","1","1"]
47+
]))

0 commit comments

Comments
 (0)