Catalogue
329. Longest Increasing Path in a Matrix
- DFS search + Memorization in Matrix!!!
1 | # Time : O(mn), Space : O(mn) |
36. Valid Sudoku
- but only meet the condition showed below can Not make sure the sudoku is valid!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution:
def isValidSudoku(self, board):
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
cubs = [set() for _ in range(9)]
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
num = board[i][j]
c = i // 3 * 3 + j // 3
if num in rows[i] or num in cols[j] or num in cubs[c]:
return False
rows[i].add(num)
cols[j].add(num)
cubs[c].add(num)
return True
37. Sudoku Solver
1 | class Solution: |
1 | class Solution: |
489. Robot Room Cleaner
- The main different thing between this dfs and others is that you have to Maintain the Direction!!!
- Backtrack: turn 2 times to revert, move 1 step, and turn 2 times to revert back.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22class Solution(object):
def cleanRoom(self, robot):
visited = set()
self.dfs(robot, 0, 0, 0, visited)
def dfs(self, robot, i, j, k, visited):
robot.clean()
visited.add((i, j))
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
for _ in range(4):
di, dj = dirs[k]
ni, nj = i + di, j + dj
if (ni, nj) not in visited and robot.move():
self.dfs(robot, ni, nj, k, visited)
robot.turnLeft()
robot.turnLeft()
robot.move()
robot.turnLeft()
robot.turnLeft()
robot.turnLeft()
k = (k + 1) % 4