Home> Java> javaTutorial> body text

Graph Traversals

WBOY
Release: 2024-08-10 06:45:09
Original
409 people have browsed it

Depth-first and breadth-first are two common ways to traverse a graph.
Graph traversalis the process of visiting each vertex in the graph exactly once. There are two popular ways to traverse a graph:depth-first traversal(ordepth-first search) andbreadth-first traversal(orbreadth-first search). Both traversals result in a spanning tree, which can be modeled using a class, as shown in Figure below. Note thatTreeis an inner class defined in theAbstractGraphclass.AbstractGraph.Treeis different from theTreeinterface defined in Searching for an Element.AbstractGraph.Treeis a specialized class designed for describing the parent–child relationship of the nodes, whereas theTreeinterface defines common operations such as searching, inserting, and deleting in a tree. Since there is no need to perform these operations for a spanning tree,AbstractGraph.Treeis not defined as a subtype ofTree.

Graph Traversals

TheTreeclass is defined as an inner class in theAbstractGraphclass in lines 226–293 in AbstractGraph.java. The constructor creates a tree with the root, edges, and a search order.

TheTreeclass defines seven methods. ThegetRoot()method returns the root of the tree. You can get the order of the vertices searched by invoking thegetSearchOrder()method. You can invokegetParent(v)to find the parent of vertexvin the search. InvokinggetNumberOfVerticesFound()returns the number of vertices searched. The methodgetPath(index)returns a list of vertices from the specified vertex index to the root. InvokingprintPath(v)displays a path from the root tov. You can display all edges in the tree using theprintTree()method.

The above is the detailed content of Graph Traversals. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!