-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ab551a4
commit 945d82a
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
class TrieNode: | ||
def __init__(self): | ||
self.links = {} | ||
self.end = False | ||
|
||
|
||
class WordDictionary: | ||
def __init__(self): | ||
self.root = TrieNode() | ||
self.maxL = 0 | ||
|
||
def addWord(self, word: str) -> None: | ||
node = self.root | ||
l = 0 | ||
|
||
for w in word: | ||
if w not in node.links: | ||
node.links[w] = TrieNode() | ||
node = node.links[w] | ||
l += 1 | ||
|
||
self.maxL = max(self.maxL, l) | ||
node.end = True | ||
|
||
## TC: O(len(word)), SC: O(1) | ||
|
||
def search(self, word: str) -> bool: | ||
if len(word) > self.maxL: | ||
return False | ||
|
||
def helper(index, node): | ||
for inn in range(index, len(word)): | ||
c = word[inn] | ||
if c == ".": | ||
for child in node.links.values(): | ||
if helper(inn + 1, child): | ||
return True | ||
return False | ||
else: | ||
if c not in node.links: | ||
return False | ||
node = node.links[c] | ||
|
||
return node.end | ||
|
||
return helper(0, self.root) | ||
|
||
## TC: O(num(node)), SC: O(len(word)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
class Solution: | ||
def numIslands(self, grid: List[List[str]]) -> int: | ||
res = 0 | ||
rows, cols, = len(grid), len(grid[0]) | ||
|
||
def dfs(x, y): | ||
if x < 0 or y < 0 or x >= rows or y >= cols or grid[x][y] == "0": | ||
return | ||
|
||
if grid[x][y] == "1": | ||
grid[x][y] = "0" | ||
dfs(x + 1, y) | ||
dfs(x - 1, y) | ||
dfs(x, y + 1) | ||
dfs(x, y - 1) | ||
|
||
for i in range(rows): | ||
for j in range(cols): | ||
if grid[i][j] == "1": | ||
dfs(i, j) | ||
res += 1 | ||
|
||
return res | ||
|
||
## TC & SC: O(m*n) |