1
A
回答
0
我自己回答
static void Main(string[] args)
{
int k = 4;
for (int i = 0; i < graph.GetLength(0); i++)
for (int j = 0; j < graph.GetLength(1); j++)
{
findNewCycles(new int[] { graph[i, j] },k);
}
foreach (int[] cy in cycles)
{
string s = "" + cy[0];
for (int i = 1; i < cy.Length; i++)
s += "," + cy[i];
Console.WriteLine(s);
}
}
static void findNewCycles(int[] path, int k)
{
int n = path[0];
int x;
int[] sub = new int[path.Length + 1];
if (path.Length < k + 1)
{
for (int i = 0; i < graph.GetLength(0); i++)
for (int y = 0; y <= 1; y = y + 2)
if (graph[i, y] == n)
// edge referes to our current node
{
x = graph[i, (y + 1) % 2];
if (!visited(x, path))
// neighbor node not on path yet
{
sub[0] = x;
Array.Copy(path, 0, sub, 1, path.Length);
// explore extended path
findNewCycles(sub,k);
}
else if ((path.Length > 2) && (x == path[path.Length - 1]))
// cycle found
{
int[] p = normalize(path);
int[] inv = invert(p);
if (isNew(p) && isNew(inv))
cycles.Add(p);
}
}
}
}
static bool equals(int[] a, int[] b)
{
bool ret = (a[0] == b[0]) && (a.Length == b.Length);
for (int i = 1; ret && (i < a.Length); i++)
if (a[i] != b[i])
{
ret = false;
}
return ret;
}
static int[] invert(int[] path)
{
int[] p = new int[path.Length];
for (int i = 0; i < path.Length; i++)
p[i] = path[path.Length - 1 - i];
return normalize(p);
}
// rotate cycle path such that it begins with the smallest node
static int[] normalize(int[] path)
{
int[] p = new int[path.Length];
int x = smallest(path);
int n;
Array.Copy(path, 0, p, 0, path.Length);
while (p[0] != x)
{
n = p[0];
Array.Copy(p, 1, p, 0, p.Length - 1);
p[p.Length - 1] = n;
}
return p;
}
static bool isNew(int[] path)
{
bool ret = true;
foreach (int[] p in cycles)
if (equals(p, path))
{
ret = false;
break;
}
return ret;
}
static int smallest(int[] path)
{
int min = path[0];
foreach (int p in path)
if (p < min)
min = p;
return min;
}
static bool visited(int n, int[] path)
{
bool ret = false;
foreach (int p in path)
if (p == n)
{
ret = true;
break;
}
return ret;
}
}
相關問題
- 1. 查找有向圖中的所有周期
- 2. 查找長度爲k的所有遞減序列的列表?
- 3. 查找數組中長度爲k的所有子集
- 4. 檢查有向圖中的週期haskell
- 5. 查找圖實現中的所有周期
- 6. 使用鄰接矩陣在C++上查找有向圖中的所有周期的算法
- 7. 查找有向圖和無向圖中的所有循環
- 8. 無向圖中最長的週期
- 9. 有K個狀態的NFA接受字符串的長度<= k
- 10. 查找誘發週期的所有邊的高效算法
- 11. Matlab的有向圖最短週期
- 12. 在圖中查找長度爲k的派系
- 13. 從長度爲k的數組獲得n上的所有組
- 14. 查找有循環的有向圖中的所有路徑
- 15. 如何檢查是否無向圖有一個奇怪的長週期
- 16. 查找可變長度週期內的最大輸出
- 17. 無向圖中最短週期的長度
- 18. 在有向圖中找到正長度的最短長度的循環
- 19. 發現列表的所有K-長度子集在序言
- 20. 使用JGrapht找到有向邊權圖中的負週期
- 21. 每個節點的DFS是否會給出有向圖中的所有周期
- 22. 查找NSArray中特定長度的所有字符串
- 23. 查找所有可能的N長度字符 - 快速替代
- 24. 查找字符串中所有子字符串的長度
- 25. 如何查找列名長度大於5的所有列?
- 26. 在加權無向圖中找到一定長度的所有路徑
- 27. 查找此有向圖中的所有路徑
- 28. 查找有向加權圖的所有生成樹
- 29. 使用面積和周長查找長度和寬度
- 30. Paypal - 結算週期長度?
爲什麼給變量有意義的名字,一個很好的例子是絕對必要的。 – BenjaminPaul 2013-03-05 20:24:14
是的,如果你可以提供一些上下文,它會有所幫助。我甚至不確定這是什麼語言。而'圖'是一個具有鄰接矩陣的全局變量?如果你可以描述你在僞代碼中做了什麼,那會很棒。 – Quantum7 2013-06-18 04:39:02
上下文似乎是[來自鏈接帖子的這個答案](http://stackoverflow.com/a/14115627/298609)。它用C#編寫,這是一個天真的實現。約翰遜給出了更好的算法。 – Paya 2017-03-28 18:42:48