Skip to content

Commit 32bc11f

Browse files
committed
adding new algos
1 parent acc98ae commit 32bc11f

2 files changed

Lines changed: 88 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
3+
class Solution:
4+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
5+
6+
# Make a grid of 0's with len(text2) + 1 columns
7+
# and len(text1) + 1 rows.
8+
len_1 = len(text1)
9+
len_2 = len(text2)
10+
dp_grid = [[0]*(len_2+1) for _ in range(len_1+1)]
11+
12+
13+
# Iterate up each column, starting from the last one.
14+
for j in reversed(range(len_2)):
15+
for i in reversed(range(len_1)):
16+
if text1[i] == text2[j]:
17+
dp_grid[i][j] = 1 + dp_grid[i+1][j+1]
18+
else:
19+
dp_grid[i][j] = max(dp_grid[i+1][j], dp_grid[i][j+1])
20+
21+
22+
# The original problem's answer is in dp_grid[0][0]. Return it.
23+
return dp_grid[0][0]
24+
25+
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from collections import deque
3+
4+
class Solution:
5+
def numIslands(self, grid: List[List[str]]) -> int:
6+
"""BFS approach - explores island level by level"""
7+
8+
if not grid:
9+
return 0
10+
11+
rows, cols = len(grid), len(grid[0])
12+
islands = 0
13+
14+
def bfs(r: int, c: int):
15+
queue = deque([(r,c)])
16+
grid[r][c] = '0'
17+
18+
while queue:
19+
row, col = queue.popleft()
20+
21+
for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
22+
nr, nc = row + dr, col + dc
23+
if (0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1'):
24+
grid[nr][nc] = '0'
25+
queue.append((nr,nc))
26+
27+
for r in range(rows):
28+
for c in range(cols):
29+
if grid[r][c] == '1':
30+
islands += 1
31+
bfs(r,c)
32+
33+
return islands
34+
35+
36+
def numIslands_DFS(grid: List[List[str]]) -> int:
37+
"""DFS approach - explores island depth-first"""
38+
39+
if not grid:
40+
return 0
41+
42+
rows, cols = len(grid), len(grid[0])
43+
islands = 0
44+
45+
def dfs(r: int, c: int):
46+
if (r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0'):
47+
return
48+
49+
grid[r][c] = '0'
50+
51+
dfs(r-1,c)
52+
dfs(r+1,c)
53+
dfs(r,c-1)
54+
dfs(r,c+1)
55+
56+
for r in range(rows):
57+
for c in range(cols):
58+
if grid[r][c] == '1':
59+
islands += 1
60+
dfs(r,c)
61+
62+
return islands
63+

0 commit comments

Comments
 (0)