# BFS（广度优先搜索算法）和DFS（深度优先搜索算法）

### ②代码：

``````package com.atlihao;

//节点类
class Node {
int x;
Node next;
public Node(int x) {
this.x = x;
this.next = null;
}
}

//DFS算法
class DFS {
public Node first;
public Node last;

public static int run[] = new int[11];
public static DFS head[] = new DFS[11];

public static void dfs(int current) {
run[current] = 1;
System.out.print("[" + current + "]");

}
}
}

public boolean isEmpty() {
return first == null;
}
public void print() {
Node current = first;
while(current != null) {
System.out.print("[" + current.x + "]");
current = current.next;
}
System.out.println();
}
public void insert(int x) {
Node newNode = new Node(x);
if(this.isEmpty()) {
first = newNode;
last = newNode;
}
else {
last.next = newNode;
last = newNode;
}
}
}

//BFS算法
class BFS {
public Node first;
public Node last;

public static int run[] = new int[11];
public static BFS head[] = new BFS[11];
public final static int MAXSIZE = 12;
static int[] queue = new int[MAXSIZE];
static int front = -1;
static int rear = -1;

public static void enqueue(int value) {
if(rear>=MAXSIZE) return;
rear++;
queue[rear] = value;
}

public static int dequeue() {
if(front == rear) return -1;
front++;
return queue[front];
}

public static void bfs(int current) {
Node tempnode;
enqueue(current);
run[current] = 1;
System.out.print("[" + current + "]");
while (front != rear) {
current = dequeue();
while (tempnode != null) {
if(run[tempnode.x] == 0) {
enqueue(tempnode.x);
run[tempnode.x] = 1;
System.out.print("[" + tempnode.x + "]");
}
tempnode = tempnode.next;
}
}
}

public boolean isEmpty() {
return first == null;
}
public void insert(int x) {
Node newNode = new Node(x);
if(this.isEmpty()) {
first = newNode;
last = newNode;
}
else {
last.next = newNode;
last = newNode;
}
}
}

public class BFSAndDFSTest {
public static void main(String[] args) {
int Data[][] = { {1,2},{1,8},{2,1},{2,3},{3,2},
{2,4},{4,2},{4,5},{4,6},{4,7}
,{5,4},{5,6},{6,4},{6,5},{6,7},{7,4},{7,6}
,{8,1},{8,9},{8,10},{9,8},{9,10},{10,9},{10,8}};
int DataNum;
int i,j;
System.out.println("图形的邻接表内容为：");
for(i=1;i<11;i++) {
DFS.run[i] = 0;
System.out.print("顶点" + i + "=>");
for (j=0;j<Data.length;j++) {
if(Data[j][0] == i) {
DataNum = Data[j][1];
}
}
}
System.out.println("深度优先遍历顶点：");
DFS.dfs(1);
System.out.println("");

for(i=1;i<11;i++) {
BFS.run[i] = 0;
for (j=0;j<Data.length;j++) {
if(Data[j][0] == i) {
DataNum = Data[j][1];
}
}
}
System.out.println("广度优先遍历顶点：");
BFS.bfs(1);
System.out.println("");
}
}
``````

### ③结果截图：

原文作者：BFS
原文地址: https://blog.csdn.net/tree_ifconfig/article/details/81325760
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。