zoukankan      html  css  js  c++  java
  • 两种优先搜索方法简述

    这两天刷了几道OJ上的搜索题,主要是深度优先搜索和广度优先搜索,简单的总结如下,

    深度优先搜索法(Depth-first Search):

    Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure, or graph.One starts at the root (selecting some node as the root in the graph case) and explores as far as possible  along each branch before backtracking.(Definition in Wiki).

    深度优先搜索属于盲目搜索(uniformed search),一般可以利用堆栈的方式实现。其范例见下面的图,它以A为根节点,搜索结果为A,B,E,F,D,C,G

    伪代码为:

    procedure dfs(vertex v)
    {
        mark v as visited
    
        for each w adjacent to v {
            if w unvisited {
                dfs(w)
            }
        }
    }  

    广度优先搜索法(Breadth-first Search)

    Breadth-first search (BFS) is a strategy for searching in a graph.The BFS begins at a root node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which were unvisited, and so on.(Definition in Wiki)

    广度优先搜索也属于盲目搜索的方法,一般使用队列实现。其范例见下图:

    伪代码为:

    procedure BFS(vertex s)
    {
        create a queue Q
        enqueue s onto Q
        mark s as visited
        while Q is not empty {
            dequeue a vertex from Q into v
            for each w adjacent to v {
                if w unvisited  {
                    mark w as visited
                    enqueue w onto Q        
                }
            }
        }
    }

    注意一点:深搜通常有递归,而广搜一个循环就搞定了。

  • 相关阅读:
    Python3.7.1学习(六)RabbitMQ在Windows环境下的安装
    使用jmeter进行简单的压测
    python中mock的使用
    python-shutil模块
    python-常用模块之os、sys
    python-冒泡排序
    python-正则基础
    python-二维数组实现90度旋转
    python-使用递归实现二分法
    python-递归的实现
  • 原文地址:https://www.cnblogs.com/soyscut/p/3185002.html
Copyright © 2011-2022 走看看