上一篇博文介绍了BFS和DFS的原理,现在给出其JAVA代码实现;

BFS就是维护一个队列,先依次访问起始点相邻的节点,入队,再访问相邻节点的相邻节点,依次入队出队。

DFS就是利用递归+回溯,直到递归到没有相邻节点可以访问了,就向上回溯。


BFS:

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
/*广度遍历是遍历到某个顶点,然后访问其连接点a,b;接着访问a的连接表,
很自然的,这种数据结构就是HashMap,以顶点为key,保存每个顶点的连接表
*/
public class BFSbak {public static void main(String args[]){BFSbak bb = new BFSbak();// s顶点的邻接表LinkedList<Character> list_s = new LinkedList<Character>();list_s.add('w');list_s.add('r');LinkedList<Character> list_w = new LinkedList<Character>();list_w.add('s');list_w.add('i');list_w.add('x');LinkedList<Character> list_r = new LinkedList<Character>();list_r.add('s');list_r.add('v');LinkedList<Character> list_x = new LinkedList<Character>();list_x.add('w');list_x.add('i');list_x.add('u');list_x.add('y');LinkedList<Character> list_v = new LinkedList<Character>();list_v.add('r');LinkedList<Character> list_i = new LinkedList<Character>();list_i.add('u');list_i.add('x');list_i.add('w');LinkedList<Character> list_u = new LinkedList<Character>();list_u.add('i');list_u.add('x');list_u.add('y');LinkedList<Character> list_y = new LinkedList<Character>();list_y.add('u');list_y.add('x');//建立邻接表HashMap<Character, LinkedList<Character>> graph = new HashMap<Character, LinkedList<Character>>();//建立邻接表的链表graph.put('s', list_s);graph.put('w', list_w);graph.put('r', list_r);graph.put('x', list_x);graph.put('v', list_v);graph.put('i', list_i);graph.put('y', list_y);graph.put('u', list_u);//建立节点的标识HashMapHashMap<Character, Integer> dist = new HashMap<Character, Integer>();char start = 's';bb.bfs(graph, dist, start);}/*HashMap<Character,LinkedList<Character>> graph* 这个HashMap是用于存放图中每个node的邻接表* 表示此映射所维护的键的类型为Character,此映射值的类型为LinkedList<Character>* graph 表示将映射关系存放在graph此映射中** LinkedList<Character> 表示在此Collection中保持元素类型为Character** HashMap<Character,Integer> dist* 这个HashMap 是用于存放每个node与距离顶点s的距离的映射关系* 表示此映射所维护的键的类型为Character* 此映射所维护的值的类型为Integer,dist表示将映射关系存放到dist此映射中*/private void bfs(HashMap<Character, LinkedList<Character>> graph,HashMap<Character, Integer> dist,char start){
//Queue<Character> 表示在此Collection中所保存的元素的类型为CharacterQueue<Character> q=new LinkedList<Character>();q.add(start);//将指定元素s插入队列,成功时返回true,如果没有可用空间,则返回illegalStateException/*put(start,0) start为指定值将要关联的键,0为指定值将要关联的值,
如果start与0的映射关系已存在,则返回并替换旧值0
如果 start与0的映射关系不存在,则返回null
*/dist.put(start, 0);int i=0;while(!q.isEmpty())//{char top=q.poll();//获取并移除队列的头,返回队列的头,如果队列为空,返回nulli++;//dist.get(top) 返回指定键top所映射的值System.out.println("The "+i+"th element:"+top+" Distance from s is:"+dist.get(top));int d=dist.get(top)+1;//得出其周边还未被访问的节点的距离/*graph.get(top)如果此映射包含一个满足 (key==null ? k==null : key.equals(k))
的从 k 键到 v 值的映射关系,则此方法返回 v;否则返回 null。(最多只能有一个这样的映射关系。)
for(元素变量:元素集合),如果元素集合中所有元素都已遍历过,则结束此循环,
否则执行for循环里的程序块
*/for (Character c : graph.get(top)){// containskey(key) 如果此映射包含对于指定键key的映射关系,则返回trueif(!dist.containsKey(c))//如果dist中还没有该元素说明还没有被访问{
/*关联指定键c与指定值d,如果关联关系已存在,则替换旧值d,返回旧值d,
如果无映射关系,则返回null*/dist.put(c, d);q.add(c); //将指定元素c插入队列,成功时返回true,如果没有可用空间,则返回illegalStateException}}}}
}

DFS:

/*** 建立链表节点*/
class Node {int x;Node next;public Node(int x) {this.x = x;this.next = null;}
}
public class BinaryTree{public Node first;  //左孩子public Node last;   //右孩子//保存访问过的节点值public static int run[] = new int[9];//建立二叉树节点数组public static BinaryTree head[] = new BinaryTree[9];/*** 访问起始某点,打上标识表示已经访问;再访问这个点的邻接点,在访问这个点的邻接点的邻接点。。一直递归下去,* 直到没有了邻接点就返回上层继续此操作;每次访问之后就打上标识表示已经访问过;最后找到所有的节点;* @param current*/public static void dfs(int current) {run[current] = 1;System.out.print("[" + current + "]");while (head[current].first != null) {if(run[head[current].first.x] == 0) { //如果顶点尚未遍历,就进行dfs递归,访问后就是1啦!!!!dfs(head[current].first.x);}head[current].first = head[current].first.next;}}//判断当前节点是否为空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;}}public static void main(String[] args) {//这此创建不同于上次的邻接表的创建;这次是直接根据图然后来写出节点对的组合,一对表示是连接在一起的邻接点;int Data[][] = { {1,2}, {2,1}, {1,3}, {3,1}, {2,4}, {4,2},{2,5}, {5,2}, {3,6}, {6,3}, {3,7}, {7,3}, {4,5}, {5,4},{6,7}, {7,6}, {5,8}, {8,5}, {6,8}, {8,6} };int DataNum;int i,j;System.out.println("图形的邻接表内容为:");for(i=1;i<9;i++) {run[i] = 0;head[i] = new BinaryTree();System.out.print("顶点" + i + "=>");for (j=0;j<20;j++) {if(Data[j][0] == i) {DataNum = Data[j][1];head[i].insert(DataNum);}}head[i].print();}System.out.println("深度优先遍历顶点:");dfs(1);System.out.println("");}
}

图:BFS/DFS java实现相关推荐

  1. 图的遍历(C语言,邻接表存储的图 - DFS,邻接矩阵存储的图 - BFS)

    邻接表存储的图 - DFS /* 邻接表存储的图 - DFS */void Visit( Vertex V ) {printf("正在访问顶点%d\n", V); }/* Visi ...

  2. [算法] 二叉树的DFS与BFS算法 (Java) -- 痛定思痛 彻底搞懂

    二叉树的DFS与BFS算法 (Java) 1.概念 ①DFS (深度优先搜索) 维基百科读一遍 定义看完, 看一遍gif ②BFS (广度优先搜索) 维基百科读一遍 gif看一遍 2. 算法实现 二叉 ...

  3. [Leetcode][第785题][JAVA][判断二分图][BFS][DFS]

    [问题描述][中等] [解答思路] 1. DFS 深度优先遍历 时间复杂度:O(N+M) 空间复杂度:O(N) class Solution {private static final int UNC ...

  4. 【八数码问题】基于状态空间法的知识表示与状态搜索:无信息搜索(BFS/DFS) 启发式搜索(A*)

    前言 一.问题引入 二.状态空间法 1. 知识及其表示 2. 状态空间法定义 3. 问题求解 三.基于状态空间搜索法解决八数码问题 1. 八数码问题的知识表示 2. 状态空间图搜索 1. 无信息搜索 ...

  5. 算法笔记-图--bfs

    题目:PAT A1076 思路: 建立图: dfs便利的的深度不超过给定深度,但是采用BFS 把节点编号和层号建立结构点,控制 #include <iostream> #include & ...

  6. 图:DFS(深度优先搜索)图解分析代码实现

    文章目录 一.简介 二.图的建立 2.1建立图类 2.2建立图 三.DFS 3.1图解 3.2代码 一.简介 图的DFS(深度优先搜索)与BFS(广度优先搜索)是图的两种遍历方式. 主要区别在于当到达 ...

  7. 全局路径规划:图搜索算法介绍1(BFS/DFS)

    对于全局路径规划的设计,我们先要了解什么是图搜索,在此之前,要先知道什么是图: 可以看到,图有很多种,有无向图,有向图,节点之间还可以有不同的weight, 用于表述从节点与节点直接迁移的代价. 而图 ...

  8. 深度搜索 java_java实现的深度搜索与广度搜索算法BFS,DFS以及几种最短路径算法...

    java实现的深度搜索与广度搜索算法BFS,DFS以及几种最短路径算法 public class City { String name; int id; static int idCounter = ...

  9. 动态规划+BFS+DFS+回溯+红黑树+排序+链表+位运算(B站优质学习资源链接,后续会继续更新)

    动态规划 正月点灯笼(UP主) 个人主页 https://space.bilibili.com/24014925/channel/detail?cid=12580 动态规划第一讲 https://ww ...

最新文章

  1. flask源码学习-路由的注册与请求处理的过程
  2. 学完了python能做什么-学会Python后都能做什么?网友们的回答简直不要太厉害
  3. kibana数据可视化
  4. 安装mamached数据库
  5. linux嵌入式开发箱跑马灯,跑马灯实验(STM32F4开发板)
  6. 汉王云名片识别(SM)组件开发详解
  7. 论文浅尝 | 用异源监督进行关系抽取:一种表示学习方法
  8. ado.net 格式 1201
  9. 各浏览器的Hack写法【转】
  10. vim mark bookmarks使用
  11. Linux的i2c通讯协议
  12. 发货100全功能网站系统源码
  13. AutoSar之CAN网络管理
  14. 台北 ModernWeb.tw 参会流水账以及感想
  15. 简约至上交互式设计四策略
  16. PPT设置“只读模式”的两种方法
  17. 逻辑回顾_回顾色彩设计
  18. 联想G480如何关闭数字小键盘
  19. 新概念英语(第四册,旧版)复习(原文及全文翻译)——Lesson 1 - Finding Fossil Man(寻找化石人)
  20. 欧姆龙plc学习笔记(四)

热门文章

  1. ButterKnife不同版本配置
  2. Android快速开发框架-ZBLibrary 源码分享
  3. 近期北京动点软件发现XXX公司盗用我公司WPF项目案例
  4. Tomcat -- Cannot create a server using the sel...
  5. Java使用PDFBox开发包实现对PDF文档内容编辑与保存
  6. Windows MDL原理总结
  7. 51单片机(STC89C52RC) IO扩展实验
  8. 【WPF】监听WPF的WebBrowser控件弹出新窗口的事件
  9. Python里面数组拼接方法介绍
  10. python提供了方法用于读取文本文件内容_python提供了哪三种方法用于读取文本文件的内容?...