Java 如何使用堆栈为图DFS添加时间戳

Java 如何使用堆栈为图DFS添加时间戳,java,data-structures,graph,depth-first-search,Java,Data Structures,Graph,Depth First Search,我有一个简短的问题。当使用DFS向后遍历树时,时间戳是如何工作的 例如 如果图形的起始节点为节点1。1到2,2到3 我已经实现了下面的一些代码。它应该返回每个顶点的开始和结束时间的2d数组 boolean[] visited = new boolean[g.getNumberOfVertices()-1] LinkedList<Integer> stack = new LinkedList<integer>(); int[][] times = new int[g.get

我有一个简短的问题。当使用DFS向后遍历树时,时间戳是如何工作的

例如

如果图形的起始节点为节点1。1到2,2到3

我已经实现了下面的一些代码。它应该返回每个顶点的开始和结束时间的2d数组

boolean[] visited = new boolean[g.getNumberOfVertices()-1]
LinkedList<Integer> stack = new LinkedList<integer>();
int[][] times = new int[g.getNumberOfVertices()][2]; //[i][0] == start,  [i][1] == end

int timer = 0;
stack.push(startingVertex);

while(!stack.isEmpty())
{
    int v = stack.pop();
    timer++;
    times[v][0] = timer; //start time
    int children = 0;
    for (int i = 0; i < g.getEdgeMatrix()[v].length; i++)
    {    
        if(g.getEdgeMatrix()[v][i] == 1)
        { 
            children++;
            if(visited[i] == false)
            {
                stack.push(i)
                visited[i] = true;
            }
         }
     }
    if(children == 0)
    {
        times[v][1] == timer + 1; // end time
    }
}

boolean[]已访问=新布尔[g.getNumberOfVertices()-1]
LinkedList堆栈=新建LinkedList();
int[][]次=新int[g.getNumberOfVertices()][2]//[i] [0]==开始,[i][1]==结束
int定时器=0;
堆栈推送(开始顶点);
而(!stack.isEmpty())
{
int v=stack.pop();
定时器++;
times[v][0]=计时器;//开始时间
int儿童=0;
对于(int i=0;i
这可能是编码错误,但我在这里有点迷路

其工作原理如下:

节点1弹出并在时间1启动。节点2添加到堆栈中,然后从时间1开始弹出。节点3添加到堆栈中,然后从时间3开始弹出。没有子节点,因此节点3的时间结束于4。堆空!在循环时退出


如何返回节点1以结束时间?

子节点
始终为0,因此
if
语句始终为真。
children
变量没有意义,应该删除。很抱歉,我想在
times[v][1]==start+1中添加children++What
start
?“如何返回节点1以结束时间?”使用递归。如果只想转到3->2->1,请按3作为起始顶点。您的代码中没有时间戳。只有一个计数器(称为计时器),当顶点从堆栈中拉出时,它会递增。
子项始终为0,因此
if
语句始终为真。
children
变量没有意义,应该删除。很抱歉,我想在
times[v][1]==start+1中添加children++What
start
?“如何返回节点1以结束时间?”使用递归。如果只想转到3->2->1,请按3作为起始顶点。您的代码中没有时间戳。只有一个计数器(称为计时器),当顶点从堆栈中拉出时,计数器会递增。