# Java 实现广度优先搜索和深度优先搜索

Java 实现广度优先搜索和深度优先搜索

1. 综述

复习算法数据结构，用Java 实现广度优先搜索和深度优先搜索。

2. 代码

Java代码：

``` 1 package cn.edu.tju.scs;
2
4 import java.util.Queue;
5
6 public class Search {
7     public static boolean [] accessed = new boolean[8];
8     public static boolean [] accessed2 = new boolean[8];
9     public static ArcNode [] heads = new ArcNode[8];
10     public static Queue<Integer> queue = new LinkedList<Integer>();
11
12     public static void main(String [] args) {
13         for (int i = 0; i < heads.length; i++) {
14             heads[i] = new ArcNode(i + 1);    // 如果节点编号也从0开始就好了，少了很多加一减一的操作
15         }
16         for (int i = 0; i < accessed.length; i++) {
17             accessed[i] = false;
18         }
21
25
29
32
35
37
39
42
45     }
46
49     }
50
51     private static void BroadFirstSearch(ArcNode arcNode) {
53         accessed2[arcNode.adjvex - 1] = true;
54         while (queue.size() > 0) {
55             Integer vex = queue.remove();
56             ArcNode curNode = heads[vex - 1].nextArc;
57             while(curNode != null) {
58                 if (!accessed2[curNode.adjvex - 1]) {
60                     accessed2[curNode.adjvex - 1] = true;
61                 }
62                 curNode = curNode.nextArc;
63             }
64             System.out.print(vex);
65             if (queue.size() > 0)
66                 System.out.print(" -> ");
67             else
68                 System.out.println("");
69         }
70     }
71
72     private static void DepthFirstSearch(ArcNode[] heads) {
74     }
75
76     private static void DepthFirstSearch(ArcNode arcNode) {
78         System.out.print(curNode);
80
81         curNode = curNode.nextArc;
82         while(curNode != null) {
84                 System.out.print(" -> ");
85                 DepthFirstSearch(curNode);
86             }
87             curNode = curNode.nextArc;
88         }
89     }
90 }```

（广搜：）1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
（深搜：）1 -> 2 -> 4 -> 8 -> 5 -> 3 -> 6 -> 7

原文作者：永哼哼
原文地址: https://www.cnblogs.com/yongheng20/p/5749957.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。