图的遍历(DFS、BFS)

理论:

深度优先搜索(Depth_Fisrst Search)遍历类似于树的先根遍历,是树的先根遍历的推广:

广度优先搜索(Breadth_First Search) 遍历类似于树的按层次遍历的过程:

java实现

Vertex.java

package 图;

public class Vertex{
    String value;
    boolean isVisited;
    Vertex(String value)
    {
        this.value=value;
        this.isVisited=false;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public boolean isVisited() {
        return isVisited;
    }
    public void setVisited(boolean isVisited) {
        this.isVisited = isVisited;
    }

}

Edge.java

package 图;

public class Edge{
    Vertex start;
    Vertex end;
    int value;
    public Vertex getStart() {
        return start;
    }

    public void setStart(Vertex start) {
        this.start = start;
    }

    public Vertex getEnd() {
        return end;
    }

    public void setEnd(Vertex end) {
        this.end = end;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    Edge(Vertex start,Vertex end, int value){
        this.start=start;
        this.end=end;
        this.value=value;
    }
}

Graph.java

package 图;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class Graph {

    public static List<Vertex> vertexList=new ArrayList<Vertex>();
    public static List<Edge> EdgeQueue=new ArrayList<Edge>();public static List<Vertex> depthVertexQueue=new ArrayList<Vertex>();
    public static List<Vertex> breathVertexQueue=new ArrayList<Vertex>();

    public static void buildGraph(){
        Vertex a=new Vertex("a");
        vertexList.add(a);
        Vertex b=new Vertex("b");
        vertexList.add(b);
        Vertex c=new Vertex("c");
        vertexList.add(c);
        Vertex d=new Vertex("d");
        vertexList.add(d);
        Vertex e=new Vertex("e");
        vertexList.add(e);
        Vertex f=new Vertex("f");
        vertexList.add(f);

        addEdge(a,b,0);
        addEdge(a,c,0);
        addEdge(b,d,0);
        addEdge(b,e,0);
        addEdge(c,f,0);

    }

    public static void addEdge(Vertex start,Vertex end,int value){
        Edge e=new Edge(start,end,value);
        EdgeQueue.add(e);
    }

public static Vertex getFirstUnvisitedNeighbor(Vertex origin){

        Vertex unvisitedNeighbor=null;
        Iterator<Edge> iterator=EdgeQueue.iterator();
        while(iterator.hasNext())
        {
            Edge edge=iterator.next();
            if(edge.getStart()==origin)
            {
                if(!edge.getEnd().isVisited)
                {
                    unvisitedNeighbor=edge.getEnd();
                    break;
                }

            }
        }
        return unvisitedNeighbor;
    }

    public static  void depthFirstVisit(Vertex origin){
        if(origin==null)
            return;
        depthVertexQueue.add(origin);
        origin.setVisited(true);

        Vertex curVertex=origin;
        Stack<Vertex> stack=new Stack<Vertex>();
        stack.add(curVertex);

        while(!stack.isEmpty())
        {
            curVertex=stack.peek();
            Vertex tempVertex=getFirstUnvisitedNeighbor(curVertex);
            if(tempVertex!=null)
            {
                depthVertexQueue.add(tempVertex);
                tempVertex.setVisited(true);
                stack.push(tempVertex);
            }
            else
            {
                stack.pop();
            }
        }

    }

    public static void breathFirstVisit(Vertex origin){
        if(origin==null)
            return;

        breathVertexQueue.add(origin);
        origin.setVisited(true);

        List<Vertex> list=new ArrayList<Vertex>();
        Vertex curVertex=origin;
        list.add(curVertex);
        while(!list.isEmpty())
        {
            curVertex=list.remove(0);
            while(getFirstUnvisitedNeighbor(curVertex)!=null)
            {
                Vertex tempVertex=getFirstUnvisitedNeighbor(curVertex);
                breathVertexQueue.add(tempVertex);
                tempVertex.setVisited(true);
                list.add(tempVertex);
            }
        }

    }

    public static void main(String[] args) {
        buildGraph();
        depthFirstVisit(vertexList.get(0));
        for(Vertex each:depthVertexQueue)
            System.out.print(each.getValue()+" ");
    }
}
时间: 2024-08-03 19:24:43

图的遍历(DFS、BFS)的相关文章

图的遍历(bfs 和dfs)

BFS的思想: 从一个图的某一个顶点V0出发,首先访问和V0相邻的且未被访问过的顶点V1.V2.……Vn,然后依次访问与V1.V2……Vn相邻且未被访问的顶点.如此继续,找到所要找的顶点或者遍历完整个图. 由此可以看出,用BFS进行搜索所搜索的顶点都是按深度进行扩展的,先找到到V0距离为1的所有顶点,然后找到距离V0为2的顶点……所以BFS所搜索到的都是最短的路径. 由于要将距离V0为d(d>0)的且未被方位的点都记录起来,我们采用队列这种数据结构.队列的特点是先进先出(FIFO),从某个顶点出

图的遍历(BFS、DFS的邻接矩阵和邻接表实现)

当年老师给我们讲这里的时候,讲的真是云里雾里的. .其实画个图就很容易理解的事情,为什么扯那么远 我觉得 DFS其实就是树的先序遍历的强化版本 BFS是层序遍历的强化 只不过 图的实现方式比较多元化 而且不像二叉树有明确的根 操作起来相对难一些 理论其实很好理解 就是具体操作起来 每次都很晕的样子 眼高手低了又. 图的遍历是指从图中的任一顶点出发,对图中的所有顶点访问一次且只访问一次.图的遍历操作和树的遍历操作功能相似.图的遍历是图的一种基本操作,图的许多其它操作都是建立在遍历操作的基础之上.

图的遍历——DFS和BFS模板(一般的图)

关于图的遍历,通常有深度优先搜索(DFS)和广度优先搜索(BFS),本文结合一般的图结构(邻接矩阵和邻接表),给出两种遍历算法的模板 1.深度优先搜索(DFS) #include<iostream> #include<unordered_map> #include<queue> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #

PAT Advanced 1034 Head of a Gang (30) [图的遍历,BFS,DFS,并查集]

题目 One way that the police finds the head of a gang is to check people's phone calls. If there is a phone call between A and B, we say that A and B is related. The weight of a relation is defined to be the total time length of all the phone calls mad

图的遍历 | 1076 bfs

bfs踩了很多坑才写完.注意:出队时不做是否vis判断,但是要加上vis[出队顶点]=1 .入队时进行判断,并且也要 vis[入队顶点]=1 #include <stdio.h> #include <memory.h> #include <math.h> #include <string> #include <vector> #include <set> #include <stack> #include <queu

图的两种遍历-DFS&amp;BFS

DFS和BFS在图中的应用: 图连通性判定:路径的存在性:图中是否存在环:求图的最小生成树:求图的关键路径:求图的拓扑排序. DFS:简单的说,先一直往深处走,直到不能再深了,再从另一条路开始往深处走,直到所有路都走完: struct node { int next; //E[i].next指向图中与i同父的下一个结点 int to; //E[i].to指向图中i的子结点 }E[110]; int N; int fa[110]; //记录各点的父结点 bool vis[110]; //记录这个点

图的遍历 DFS和BFS

深度优先搜索 (Depth First Search, DFS): void DFS ( Vertex V ) { visited[ V ] = true; for ( V 点 的每个邻接点 W ) if ( !visited[ W ] ) DFS( W ); } 若有N 个顶点.E 条边,时间复杂度是 用邻接表存储图,有O(N+E) 用邻接矩阵存储图,有O(N 2 ) 广度优先搜索 (Breadth First Search, BFS) void BFS ( Vertex V ) { visi

PAT Advanced 1076 Forwards on Weibo (30) [图的遍历,BFS,DFS]

题目 Weibo is known as the Chinese version of Twitter. One user on Weibo may have many followers, and may follow many other users as well. Hence a social network is formed with followers relations. When a user makes a post on Weibo, all his/her followe

图的遍历(bfs+dfs)模板

bfs 1 #include<iostream> 2 #include<queue> 3 #include<cstdio> 4 using namespace std; 5 queue<int>q; 6 int map[1001][1001]; 7 int vis[1001]; 8 int n,m; 9 void bfs(int p) 10 { 11 q.push(p); 12 vis[p]=1; 13 printf("%c-->"