图的遍历(广度和深度)


//深度优先遍历****************************************************
class Graph1 { //以邻接矩阵存储的图类

protected int n; //图的节点个数
protected int mat[][]; // 二维数组存储图的邻接矩阵
protected int visited[]; //访问标记数组

public Graph1(int m1[][]){
n = m1.length;
mat = new int [n][n];
System.arraycopy(m1, 0, mat, 0, n); //System类方法,复制数组
visited= new int [n];
}
public Graph1(){
}
public void depthFirstSearch(){ //图的深度优先遍历
System.out.println("深度优先遍历Depth first search:");
for(int k=1;k<=n;k++){
depthfs(k);
System.out.println();
unvisited();
}
}
private void unvisited() {
int i;
for(i = 0;i<visited.length;i++){
visited[i]=0;
}
}
private void depthfs(int k) { //从节点k开始的深度优先遍历
int i,j=0;
System.out.print(" v"+k+"->");
i = k - 1;
visited[i]=1;
while(j<n){
if(mat[i][j]==1 && visited[j]==0){
depthfs(j+1);
}else {
j++;
}
}
}
}
public class testGraph1{
public static void main(String ag[]){
int mat[][]= {{0,1,0,0},{0,0,1,1},{0,0,0,0},{1,0,1,0}};
Graph1 g1 = new Graph1(mat);
g1.depthFirstSearch();
}
}

//广度优先遍历*****************************************************
public class OnelinkNode { //单向链表的节点结构
public int data;
public OnelinkNode next;
public OnelinkNode(int k){ //构造值为k的节点
data = k;
next = null;
}
public OnelinkNode(){
this(0);
}
}

public class Graph2 extends Graph1 { //以邻接表存储的图类
OnelinkNode table[]; //图的邻接表

public Graph2(int mat[][]){ //以邻接矩阵的形式建立图的邻接表
n = mat.length; // 继承Graph1类的成员
table = new OnelinkNode[n+1]; //建立节点表,多一个元素
OnelinkNode p = null, q;
int i ,j ;
for(i = 1; i<= n;i++){ //table[0]不用 节点序号i与table中的 下标一致
table[i] = new OnelinkNode(i); //创建i在节点表中的元素
p = table[i]; //建立节点i的出边表
for(j = 1; j<=n;j++){ //查找与i相邻的其他节点j
if(mat[i-1][j-1]==1){
q = new OnelinkNode(j);
p.next = q;
p = q;
}
}
visited = new int [n +1];
}
}
public Graph2(){}

public void output(){
OnelinkNode p;
System.out.println("邻接表table:");
for(int i=0;i<table.length;i++){
System.out.print("table["+i+"]=");
if(table[i]!=null){
System.out.print("v"+table[i].data);
p = table[i].next;
while(p != null){
System.out.print("->v"+p.data);
p = p.next;
}
}
System.out.println(" null");
}

}


/* public void depthfs(int k){
int i , j = 0;
OnelinkNode p ;
System.out.print(" v" +k+" ->");
i = k;
visited[i]=1;
if(table[i]!=null){
p = table[i].next;
while(p !=null){
j = p.data;
if(visited[j]==0){
depthfs(j);
}else{
p = table[i].next;
}
}
}
}
*/
public static void main(String args[]){
int mat[][]= {{0,1,0,0},{0,0,1,1},{0,0,0,0},{1,0,1,0}};
Graph2 g2 = new Graph2(mat); //现在的g2已经是一个邻接表了不是邻接矩阵了
g2.output();


}
}
//邻接表table:
//table[0]= null
//table[1]=v1->2->4 null
//table[2]=v2->1->3->4 null
//table[3]=v3->2->4 null
//table[4]=v4->1->2->3 null


    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/hnzgemail/article/details/84371218
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞