-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathUnique_3D_Visualization_of_Hamiltonian_Cycle.py
51 lines (42 loc) · 1.62 KB
/
Unique_3D_Visualization_of_Hamiltonian_Cycle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from itertools import permutations
import time
def is_hamiltonian_cycle(graph):
n = len(graph)
vertices = list(range(n))
for perm in permutations(vertices):
if graph[perm[-1]][perm[0]] == 1: # Check if the last vertex is connected to the first vertex
if all(graph[perm[i]][perm[i+1]] == 1 for i in range(n-1)): # Check if other vertices are connected in the permutation
return True
return False
# Example graph represented as an adjacency matrix
graph_matrix = np.array([[0, 1, 1, 0],
[1, 0, 1, 1],
[1, 1, 0, 1],
[0, 1, 1, 0]])
# Create a NetworkX graph from the adjacency matrix
G = nx.Graph(graph_matrix)
# Create 3D coordinates for nodes manually
pos_3d = {0: (1, 1, 1), 1: (1, 2, 1), 2: (2, 1, 1), 3: (2, 2, 1)}
# Create an initial empty 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the graph in 3D
edge_trace = None
for edge in G.edges():
x0, y0, z0 = pos_3d[edge[0]]
x1, y1, z1 = pos_3d[edge[1]]
line = [(x0, y0, z0), (x1, y1, z1)]
edge_trace = Line3DCollection([line], color='blue', linewidths=2) if edge_trace is None else \
Line3DCollection([line], color='blue', linewidths=2, alpha=0.3)
ax.add_collection3d(edge_trace)
# Set axis labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Unique 3D Visualization of Hamiltonian Cycle')
plt.show()