使用DFS查找联通分量
最初的回答
import queue
import itertools
n = 10
def DFS(data, v, x,y,z, component):
q = queue.Queue()
q.put((x,y,z))
while not q.empty():
x,y,z = q.get()
v[x,y,z] = component
l = [[x], [y], [z]]
for i in range(3):
if l[i][0] > 0:
l[i].append(l[i][0]-1)
if l[i][0] < v.shape[1]-1:
l[i].append(l[i][0]+1)
c = list(itertools.product(l[0], l[1], l[2]))
for x,y,z in c:
if v[x,y,z] == 0 and data[x,y,z] == 1:
q.put((x,y,z))
data = np.random.binomial(1, 0.2, n*n*n)
data = data.reshape((n,n,n))
coordinates = np.argwhere(data > 0)
v = np.zeros_like(data)
component = 1
for x,y,z in coordinates:
if v[x,y,z] != 0:
continue
DFS(data, v, x,y,z, component)
component += 1
最初的回答:
主要算法:
- 将每个点的visited设为0(表示它尚未成为任何连通组件的一部分)
- 对于所有值等于1的点:
- 如果该点未被访问,请从该点开始进行深度优先搜索(DFS)
DFP:这是使用队列的传统DFS算法。在3D情况下,唯一不同的是,给定(x,y,z),我们使用itertools.product计算其所有有效邻居。在3D情况下,每个点都有27个邻居,包括自身(3个位置和3个可能的值-相同、增量、减量,因此有27种方法)。
矩阵v存储从1开始编号的连通组件。
测试用例:
当数据为
[[[1 1 1]
[1 1 1]
[1 1 1]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[1 1 1]
[1 1 1]
[1 1 1]]]
可视化:
这个算法返回节点v,其中两个相对的边是两个不同的连通分量。
[[[1 1 1]
[1 1 1]
[1 1 1]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[2 2 2]
[2 2 2]
[2 2 2]]]
"最初的回答"
正确的。
可视化:
如可视化所示,绿色表示一个连通分量,蓝色表示另一个连通分量。
可视化代码。
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plot(data):
fig = plt.figure(figsize=(10,10))
ax = fig.gca(projection='3d')
for i in range(data.shape[0]):
for j in range(data.shape[1]):
ax.scatter([i]*data.shape[0], [j]*data.shape[1],
[i for i in range(data.shape[2])],
c=['r' if i == 0 else 'b' for i in data[i,j]], s=50)
plot(data)
plt.show()
plt.close('all')
plot(v)
plt.show()