For the graphs with dense edges, the adjacency matrix (vertex-centric) can be expressed, and the adjacency table structure is more suitable when the edges are sparse. Neither can visually express which two points are connected or what the shortest path is.
Depth-first traversal is similar to a tree's first root sequence traversal. Unlike a tree, it needs to add a tag to a node that has already been visited to avoid repeated traversal.
public class Depth {
/**
* to k node depth traversal
* @param a
* @param color
* @param k node
/public static void Depthtraversal (int[][] a,int[] color,int k) {
System.out.println (k);
color[k]=1;//0 not stained, 1 staining indicates traversing
//finding A for
(int i=0;i<a[k].length;i++) {
if (a[k][i]==1&&) connection with K color[i]==0) {
depthtraversal (a,color,i);
}
}} /**
* @param args
/public static void main (string[] args) {
//adjacency matrix tag is connected, 1 means connected, 0 means not even
int[] [] a={
{0,1,1,1,0},
{1,0,1,1,1}, {
1,1,0,1,1},
{1,1,0,0,1},
{1,1,1,1,0}
};
An array is required to record the staining information,
int[] color=new The internal default value of the Int[a.length];//int array is 0
depthtraversal (a,color,0);
}
Breadth-first traversal is similar to traversing a tree in layers. It is traversed from near to far according to the distance from the start node. Of course, because of the characteristics of the graph, we also need to mark the traversed nodes.
Import java.util.ArrayList;
Import Java.util.HashSet;
Import java.util.List;
Import Java.util.Set;
public class Breadth {
/**
* @param args
*
/@SuppressWarnings ("unchecked") public
static void main (string[] args) {
//adjacency matrix tag is connected, dense graph, our writing can be adjacency table
int[][] a={
{0,1,1,1,0,1},
{1,0,1,1,1,0},
{1,1,0,0,1,1 },
{1,1,0,0,1,0}, {0,1,1,1,0,0}, {
1,0,1,0,0,0}}
;
Breadth Traverse
List lst=new ArrayList ()//wait
to traverse Set set=new hashset ();//Save traversed Node
lst.add (0);//First add 0 nodes
while (true) {
if (Lst.isempty ()) break;
int node= (Integer) lst.get (0);
SYSTEM.OUT.PRINTLN (node);
Set.add (node);
Lst.remove (0);
for (int i=0;i<a[node].length;i++) {
//connected, not traversed, LST does not contain the node (possibly the child of the next node in the child of this node)
if (a[node][i]==1& &set.contains (i) ==false&&lst.indexof (i) ==-1) {
lst.add (i);
}
}
}}
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/