//邻接表实现图的广搜和深搜(java模板)

Java代码
  1. import java.util.*;
  2.  
  3. public class GraphSearch{
  4. private int n; //图的顶点数,顶点为0,1,2,,,,n-1
  5.  
  6. private List> G;// 邻接表实现图。
  7. private boolean[] visited;//判断顶点是否被访问过
  8.  
  9. public GraphSearch(int n,List> G){
  10. this.n=n;
  11. this.G=G;
  12. visited = new boolean[n];
  13.  
  14. }
  15.  
  16. public static void main(String[] args) {
  17. int n,m;
  18. List> G;
  19. Scanner sc = new Scanner(System.in);
  20. n = sc.nextInt();
  21. m = sc.nextInt();
  22. G = new ArrayList>();
  23. for(int i = 0;i
  24. G.add(new ArrayList());//初始化邻接表
  25. for(int i=0;i
  26. int u = sc.nextInt();
  27. int v = sc.nextInt();
  28. if(!G.get(u).contains(v)) {// 避免重边的情况比如a b可能出现两次的情况
  29. G.get(u).add(v);
  30.  
  31. }
  32. //对于无向图
  33. if(!G.get(v).contains(u)) {
  34. G.get(v).add(u);
  35.  
  36. }
  37. }
  38. GraphSearch ma=new GraphSearch(n,G);
  39. //ma.dfs(0);
  40. ma.bfs(0);
  41.  
  42. }
  43.  
  44.  
  45. // 深搜
  46. private void dfs(int v) {
  47. visited[v] = true;
  48. System.out.print(v+" ");
  49.  
  50. for (int i = 0; i
  51. //递归调用搜索没有被访问过的当前节点的下一个节点(邻接点)
  52. int k=G.get(v).get(i);
  53. if (!visited[k])
  54. dfs(k);
  55. }
  56.  
  57. }
  58.  
  59. //广搜
  60. private void bfs(int v) {
  61. //队列用来保存被访问节点的分支节点(邻接点)
  62. Queue que = new LinkedList();
  63. que.offer(v);
  64. while (!que.isEmpty()) {
  65. v = que.poll();
  66. System.out.print(v+" ");
  67. visited[v] = true;
  68. //将被访问节点的分支节点(邻接点)加入到队列中
  69. for (int i = 0; i
  70. int k=G.get(v).get(i);
  71. if (!visited[k]){
  72. que.add(k);
  73. visited[k] = true;
  74. }
  75. }
  76. }
  77. }
  78. }