西西河

主题:再次请教河里的高手,一个图论问题 -- 棒棒糖

共:💬26 🌺15 新:
全看分页树展 · 主题 跟帖
家园 用c#实现的

用一个2维数组定义所以可能的通路,比如元素paths[i,j]=0表示i节点到j节点不通,而1表示可通,那你所举的例子实现如下

int[,] paths = new int[6,6] { { 0, 1, 1, 1, 1, 1 }, { 0, 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 1, 1 }, { 0, 1, 1, 0, 1, 1 }, { 0, 0, 1, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0 } };

private ArrayList pathList = new ArrayList();

private ArrayList curPath = new ArrayList();

private void Doit()

{

for (int i = 0; i <= 5; i++)

{

GetPaths(i);

}

}

private void GetPaths(int startNode)

{

curPath.Add(startNode);

if (curPath.Count == 6)

{

pathList.Add(((int)curPath[0] + 1).ToString() + ((int)curPath[1] + 1).ToString() + ((int)curPath[2] + 1).ToString() + ((int)curPath[3] + 1).ToString() + ((int)curPath[4] + 1).ToString() + ((int)curPath[5] + 1).ToString());

curPath.Remove(startNode);

return;

}

for (int j = 0; j <= 5; j++)

{

if ((paths[startNode, j] == 1) && !curPath.Contains(j))

{

GetPaths(j);

}

}

curPath.Remove(startNode);

return;

}

全看分页树展 · 主题 跟帖


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河