图的遍历(广度和深度)

来源:互联网 发布:华为mate9数据恢复 编辑:程序博客网 时间:2024/06/10 04:19
Java代码 复制代码 收藏代码
  1. //深度优先遍历****************************************************
  2. class Graph1 { //以邻接矩阵存储的图类
  3. protected int n; //图的节点个数
  4. protected int mat[][];// 二维数组存储图的邻接矩阵
  5. protected int visited[];//访问标记数组
  6. public Graph1(int m1[][]){
  7. n = m1.length;
  8. mat = new int [n][n];
  9. System.arraycopy(m1, 0, mat, 0, n); //System类方法,复制数组
  10. visited= new int [n];
  11. }
  12. public Graph1(){
  13. }
  14. public void depthFirstSearch(){//图的深度优先遍历
  15. System.out.println("深度优先遍历Depth first search:");
  16. for(int k=1;k<=n;k++){
  17. depthfs(k);
  18. System.out.println();
  19. unvisited();
  20. }
  21. }
  22. private void unvisited() {
  23. int i;
  24. for(i = 0;i<visited.length;i++){
  25. visited[i]=0;
  26. }
  27. }
  28. private void depthfs(int k) {//从节点k开始的深度优先遍历
  29. int i,j=0;
  30. System.out.print(" v"+k+"->");
  31. i = k - 1;
  32. visited[i]=1;
  33. while(j<n){
  34. if(mat[i][j]==1 && visited[j]==0){
  35. depthfs(j+1);
  36. }else {
  37. j++;
  38. }
  39. }
  40. }
  41. }
  42. public class testGraph1{
  43. public static void main(String ag[]){
  44. int mat[][]= {{0,1,0,0},{0,0,1,1},{0,0,0,0},{1,0,1,0}};
  45. Graph1 g1 = new Graph1(mat);
  46. g1.depthFirstSearch();
  47. }
  48. }