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        
                }
            }
        }
    }

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

  • 相关阅读:
    Metro-Ural119递推
    Flags-Ural1225简单递推
    Candies-POJ3159差分约束
    Is the Information Reliable? -POJ2983差分约束
    MPI Maelstrom
    Codeforces Round #342 (Div. 2)-B. War of the Corporations
    Codeforces Round #342 (Div. 2)-A. Guest From the Past
    Vim升华之树形目录插件NERDTree安装图解
    The Same Game-POJ1027模拟
    Flesch Reading Ease -POJ3371模拟
  • 原文地址:https://www.cnblogs.com/soyscut/p/3185002.html
Copyright © 2011-2022 走看看