图
实现有向图、无向图、有权图、无权图的邻接矩阵和邻接表表示方法
实现图的深度优先搜索、广度优先搜索
实现 Dijkstra 算法、A* 算法
实现拓扑排序的 Kahn 算法、DFS 算法
对应的 LeetCode 练习题
目录:
1,leetcode-200;
2,leetcode-363。
1,Number of Islands(岛屿的个数):
英文版:https://leetcode.com/problems/number-of-islands/description/中文版:https://leetcode-cn.com/problems/number-of-islands/description/
class Solution:
def numIslands(self, grid):
res = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == "1":
self.dfs(grid, r, c)
res += 1
return res
def dfs(self, grid, i, j):
dirs = [[-1, 0], [0, 1], [0, -1], [1, 0]]
grid[i][j] = "0"
for dir in dirs:
nr, nc = i + dir[0], j + dir[1]
if nr >= 0 and nc >= 0 and nr < len(grid) and nc < len(grid[0]):
if grid[nr][nc] == "1":
self.dfs(grid, nr, nc)
2,Valid Sudoku(有效的数独):
英文版:https://leetcode.com/problems/valid-sudoku/中文版:https://leetcode-cn.com/problems/valid-sudoku/
class Solution:
def isValidSudoku(self, board):
raw = [{},{},{},{},{},{},{},{},{}]
col = [{},{},{},{},{},{},{},{},{}]
cell = [{},{},{},{},{},{},{},{},{}]
for i in range(9):
for j in range(9):
num = (3*(i//3) + j//3)#找单元
temp = board[i][j]
if temp != ".":
if temp not in raw[i] and temp not in col[j] and temp not in cell[num]:
raw [i][temp] = 1
col [j][temp] = 1
cell [num][temp] =1
else:
return False
return True