Looking for algorithm finding euler path

后端 未结 5 747
终归单人心
终归单人心 2021-02-05 13:45

I\'m looking for an algorithm to find an Euler path in a graph.

I\'ve seen a good one a couple of weeks ago but I can\'t find it now, I remember there was tagging edges

5条回答
  •  北海茫月
    2021-02-05 14:27

    Soo this is my solution , i've used finally block to print out because i get exception "stack is empty" and i don't really have time to fix that. I hope this helps someone!

    public void EulerTour()
        {
            GetInput(); //gets the adjency matrix
    
            int start = NodeList[0]; //start from any vertex, i choose 0
            tempPath.Push(NodeList[0]); //temporary path - stack
            try
            {
                while (tempPath.Count != 0) 
                {
                    for (int i = 0; i < total; i++)
                    {
                        if (adjencyMatrix[start, i] == 'd')
                        {
                            tempPath.Push(NodeList[i]);
                            adjencyMatrix[start, i] = 'n';
                            adjencyMatrix[i, start] = 'n';
    
                            if (!hasNeighbour((int)tempPath.Peek())) //checks if current node has any neighbour
                            {
                                while (!hasNeigbour((int)tempPath.Peek()))
                                {
                                    finalPath.Push(tempPath.Pop());
    
                                }
                                start = (int)tempPath.Peek();
                            }
                            else
                            {
                                start = i;
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                Console.WriteLine("Print: ");
            }
            finally
            {
                foreach (object o in finalPath)
                {
                    Console.Write(o.ToString() + "---->");
                }
            }     
            Console.ReadKey();            
        }
    

提交回复
热议问题