擅长:python、mysql、java
<p>我认为把你的图变成矩阵形式会让你很难去思考。将边缘连接列表转换为连接节点的列表将使事情变得更简单(并且,作为一个额外的好处,在<code>society()</code>将返回<code>False</code>的情况下减少计算负载,随着节点数量的增加,这一点更为重要):</p>
<pre class="lang-python prettyprint-override"><code>def to_map(gmatrix):
return [[k for k,v in enumerate(edges) if v] for edges in gmatrix]
</code></pre>
<p>然后你就能做到:</p>
<pre class="lang-python prettyprint-override"><code>def society(graph_map, node):
for n in graph_map[node]:
if n == node:
continue
for nn in graph_map[n]:
if nn != node and nn != n and nn in graph_map[node]:
return True
return False
</code></pre>
<p>例如:</p>
<pre class="lang-python prettyprint-override"><code>gmatrix = [ [0,1,1,1,0],
[1,0,0,1,0],
[1,0,0,0,1],
[1,1,0,0,0],
[0,0,1,0,0] ]
gmap = to_map(gmatrix)
print(society(gmap,0)) # True
print(society(gmap,2)) # False
</code></pre>