Skip to content

Commit 337bb79

Browse files
committed
leetcode.com 200. Number of Islands
문제 링크: https://leetcode.com/problems/number-of-islands/description/
1 parent 5e1c6aa commit 337bb79

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def numIslands(self, grid: List[List[str]]) -> int:
6+
MAX_ROW = len(grid)
7+
MAX_COL = len(grid[0])
8+
answer = 0
9+
10+
dyx = [[1, 0], [0, 1], [-1, 0], [0, -1]]
11+
12+
for row in range(MAX_ROW):
13+
for col in range(MAX_COL):
14+
if grid[row][col] == '1':
15+
queue = [[row, col]]
16+
grid[row][col] = 0
17+
answer += 1
18+
19+
while queue:
20+
y, x = queue.pop(0)
21+
22+
for dy, dx in dyx:
23+
ny, nx = y + dy, x + dx
24+
if 0 <= ny < MAX_ROW and 0 <= nx < MAX_COL and grid[ny][nx] == '1':
25+
queue.append([ny, nx])
26+
grid[ny][nx] = 0
27+
28+
return answer
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from unittest import TestCase
2+
from main import Solution
3+
4+
5+
class TestSolution(TestCase):
6+
def test1_num_islands(self):
7+
sol = Solution()
8+
self.assertEqual(1, sol.numIslands([
9+
["1","1","1","1","0"],
10+
["1","1","0","1","0"],
11+
["1","1","0","0","0"],
12+
["0","0","0","0","0"]
13+
]))

0 commit comments

Comments
 (0)