You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.2 KiB
47 lines
1.2 KiB
# -*- coding: utf-8 -*-
|
|
# Time : 2023/11/3 17:43
|
|
# Author : lirunsheng
|
|
# User : l'r's
|
|
# Software: PyCharm
|
|
# File : dfs.py
|
|
|
|
import numpy as np
|
|
def dfs_exists_path(distances):
|
|
num_cities = distances.shape[0]
|
|
visited = set()
|
|
start_node = 0
|
|
|
|
def dfs(node):
|
|
visited.add(node)
|
|
for neighbor in range(num_cities):
|
|
if neighbor != node and neighbor not in visited and np.isfinite(distances[node, neighbor]):
|
|
dfs(neighbor)
|
|
|
|
dfs(start_node)
|
|
|
|
return len(visited) == num_cities
|
|
|
|
|
|
def exists_path_without_inf(distances):
|
|
# Check if there are any infinite distances
|
|
if np.any(np.isinf(distances)):
|
|
return False
|
|
|
|
# Set the infinite distances to a large value
|
|
max_distance = np.max(distances) + 1
|
|
distances[np.isinf(distances)] = max_distance
|
|
|
|
# Use DFS to check if there exists a path
|
|
return dfs_exists_path(distances)
|
|
|
|
|
|
distances = np.array([
|
|
[np.inf, 50, 99, np.inf, 64, np.inf],
|
|
[50, np.inf, 12, 45, 74, 13],
|
|
[99, 12, np.inf, 25, np.inf, 61],
|
|
[np.inf, 45, 25, np.inf, 45, 47],
|
|
[64, 74, np.inf, 45, np.inf, np.inf],
|
|
[np.inf, 13, 61, 47, np.inf, np.inf]
|
|
])
|
|
|
|
print(exists_path_without_inf(distances)) |