代码实现
/** * */ package test; /** * * @author Jeffrey * @date 2017年5月3日 * @weibo ouc大飞 * @qq 1020724110 */ public class Graph1 {//以邻接矩阵存储的图类 protected int n;//节点的个数 protected int mat[][];//二维数组存储图的邻接矩阵 protected int visited[];//访问标记数组 public Graph1(int m1[][]){ n=m1.length; mat=new int [n][n]; //mat=m1; System.arraycopy(m1, 0, mat, 0, n); 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 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++; } } } private void unvisited() { int i; for(i = 0;i<visited.length;i++){ visited[i]=0; } } public static void main(String[] args) { int mat1[][]={{0,1,0,1}, //无向图G6的邻接矩阵 {1,0,1,1}, {0,1,0,1}, {1,1,1,0}}; Graph1 g1=new Graph1(mat1); g1.depthFirstSearch(); } }