java 递归 dfs,迭代DFS与递归DFS和不同元素顺序

下面是C#for Adjacency Matrix中的示例代码(根据上面的@amit回答) .

using System;

using System.Collections.Generic;

namespace GraphAdjMatrixDemo

{

public class Program

{

public static void Main(string[] args)

{

// 0 1 2 3 4 5 6

int[,] matrix = { {0, 1, 1, 0, 0, 0, 0},

{1, 0, 0, 1, 1, 1, 0},

{1, 0, 0, 0, 0, 0, 1},

{0, 1, 0, 0, 0, 0, 1},

{0, 1, 0, 0, 0, 0, 1},

{0, 1, 0, 0, 0, 0 ,0},

{0, 0, 1, 1, 1, 0, 0} };

bool[] visitMatrix = new bool[matrix.GetLength(0)];

Program ghDemo = new Program();

for (int lpRCnt = 0; lpRCnt < matrix.GetLength(0); lpRCnt++)

{

for (int lpCCnt = 0; lpCCnt < matrix.GetLength(1); lpCCnt++)

{

Console.Write(string.Format(" {0} ", matrix[lpRCnt, lpCCnt]));

}

Console.WriteLine();

}

Console.Write("\nDFS Recursive : ");

ghDemo.DftRecursive(matrix, visitMatrix, 0);

Console.Write("\nDFS Iterative : ");

ghDemo.DftIterative(matrix, 0);

Console.Read();

}

//====================================================================================================================================

public void DftRecursive(int[,] srcMatrix, bool[] visitMatrix, int vertex)

{

visitMatrix[vertex] = true;

Console.Write(vertex + " ");

for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)

{

if (visitMatrix[neighbour] == false && srcMatrix[vertex, neighbour] == 1)

{

DftRecursive(srcMatrix, visitMatrix, neighbour);

}

}

}

public void DftIterative(int[,] srcMatrix, int srcVertex)

{

bool[] visited = new bool[srcMatrix.GetLength(0)];

Stack vertexStack = new Stack();

vertexStack.Push(srcVertex);

while (vertexStack.Count > 0)

{

int vertex = vertexStack.Pop();

if (visited[vertex])

continue;

Console.Write(vertex + " ");

visited[vertex] = true;

for (int neighbour = srcMatrix.GetLength(0) - 1; neighbour >= 0; neighbour--)

//for (int neighbour = 0; neighbour < srcMatrix.GetLength(0); neighbour++)

{

if (srcMatrix[vertex, neighbour] == 1 && visited[neighbour] == false)

{

vertexStack.Push(neighbour);

}

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值