|
- def count_paths():
- max_x = 6
- max_y = 4
- start = (0, 0)
- end = (6, 4)
- # 记录哪些点已经被访问过
- visited = [[False for _ in range(max_y + 1)] for _ in range(max_x + 1)]
- # 检查点是否在网格内且未被访问
- def is_valid(x, y):
- return 0 <= x <= max_x and 0 <= y <= max_y and not visited[x][y]
- directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
- def backtrack(current_x, current_y):
- if (current_x, current_y) == end:
- return 1
- count = 0
- for dx, dy in directions:
- next_x, next_y = current_x + dx, current_y + dy
- if is_valid(next_x, next_y):
- visited[next_x][next_y] = True
- count += backtrack(next_x, next_y)
- visited[next_x][next_y] = False
- return count
- visited[start[0]][start[1]] = True
- total_paths = backtrack(start[0], start[1])
- return total_paths
- print(count_paths())
Copy the Code 写了一段 Python 代码,输出 752061 |
|