DFS

权当备忘了

主要参考《数据结构严尉敏版》

但是是c++实现

ContractedBlock.gif ExpandedBlockStart.gif Code
#include<iostream>
#include
<vector>
using namespace std;

class AdjListGraph
{
public:
    AdjListGraph();
    
~AdjListGraph(); 
    
int NumberOfVertex()          //query for number of vertex
    {
        
return VexNum;
    }
    
int NumberOfArc()             //query for number of arc
    {
        
return ArcNum;
    }
    
void DFSTraverse();
    
void BFSTraverse();
    
private:
    
struct ArcNode
    {
        ArcNode(
int aAdjVex = -1, ArcNode *aNextArc = NULL, int aInfo = -1)
            : AdjVex(aAdjVex), NextArc(aNextArc), info(aInfo) {}
        
int AdjVex;               //当前弧指向的节点位置
        ArcNode *NextArc;         //指向下一条弧的指针
        int info;                 //该弧相关信息的指针
    };
    
struct VNode
    {
        VNode(
int vData = -1, ArcNode *vFirstArc = NULL)
            : data(vData), FirstArc(vFirstArc) {}
        
int data;                 //information of the Node
        ArcNode *FirstArc;        //the first arc adjacent to the Node
    };
    
    
static const int MaxVextexNum = 100;
    VNode AdjList[MaxVextexNum];
    
int VexNum;                   //number of Vetices
    int ArcNum;                   //number of arcs
    int kind;                     //kind of graph, 0 stand for
                                  
//undigraph, 1 for digraph

    
static const int NoPosition = -1;
    
bool visited[MaxVextexNum];
    
int FirstAdjVex(int vex);
    
int NextAdjVex(int vex, int curVex);
    
void DFS(int vex);
};

AdjListGraph::AdjListGraph()
{
    cout 
<< "Please input the VexNum and ArcNum of the Graph in order: " << endl;
    cout 
<< "VexNum: ";
    cin 
>> VexNum;
    cout 
<< "ArcNum: ";
    cin 
>> ArcNum;
    cout 
<< "Next, pleast input the information of each vertex: " << endl;
    
for(int i = 0; i < VexNum; i++)
    {
        cout 
<< "the information of " << i
             
<< "th vertex: ";
        cin 
>> AdjList[i].data;
    }
    cout 
<< "Next, pleast input the information of the arc:"
         
<< endl;

    
for(int i = 0; i < ArcNum; i++)
    {
        
int begin;
        
int end;
        cout 
<< "Pleast input the begin and end position of "
             
<< i << "th arc: " << endl;
        cout 
<< "begin position: ";
        cin 
>> begin;
        cout 
<< "end position: ";
        cin 
>> end;
        ArcNode 
*ptrArc1 = new ArcNode(end, AdjList[begin].FirstArc);
        AdjList[begin].FirstArc 
= ptrArc1;
        ArcNode 
*ptrArc2 = new ArcNode(begin, AdjList[end].FirstArc);
        AdjList[end].FirstArc 
= ptrArc2;
    }
}

AdjListGraph::
~AdjListGraph()
{
    
for(int i = 0; i < VexNum; i++)
    {
        ArcNode 
*p;
        p 
= AdjList[i].FirstArc;

        
if(p != NULL)
        {
            ArcNode 
*= p;
            p 
= p->NextArc;
            delete q;
        }
    }
}

void AdjListGraph::DFSTraverse()
{
    
int vex;
    
for(vex = 0; vex < VexNum; vex++)
        visited[vex] 
= false;
    
for(vex = 0; vex < VexNum; vex++)
        
if(!visited[vex])
            DFS(vex);
}

inline 
int AdjListGraph::FirstAdjVex(int vex)
{
    
return AdjList[vex].FirstArc->AdjVex;
}

int AdjListGraph::NextAdjVex(int vex, int curVex)
{
    ArcNode 
*ptrArc = AdjList[vex].FirstArc;

    
while(ptrArc->NextArc != NULL)
    {
        
if(ptrArc->AdjVex == curVex)
            
return ptrArc->NextArc->AdjVex;
        
else
            ptrArc 
= ptrArc->NextArc;
    }

    
return NoPosition;
}
void AdjListGraph::DFS(int vex)
{
    visited[vex] 
= true;
    cout 
<< "Vex: " << vex << " Vex->data: " << AdjList[vex].data << endl;
    
for(int w = FirstAdjVex(vex); w >= 0; w = NextAdjVex(vex, w))
    {
        
if(!visited[w])
            DFS(w);
    }
}

int main()
{
    AdjListGraph G;
    G.DFSTraverse();
        
    
return 0;
}

 

转载于:https://www.cnblogs.com/cnlox/archive/2009/04/08/1431922.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
06-01
DFS(Depth First Search,深度优先搜索)是一种搜索算法,用于在树或图等数据结构中遍历所有节点。DFS 从起始节点开始,沿着一条路径一直遍历到底,直到不能再前进为止,然后返回上一个节点,继续遍历其它路径。DFS 可以用递归或栈来实现。 在 DFS 中,我们可以分为两种遍历方式:深度优先遍历(preorder)、后序遍历(postorder)。深度优先遍历从根节点开始,一直遍历到叶子节点,然后返回上一级节点,进行下一轮遍历。后序遍历则是遍历完子节点之后,再遍历父节点。这两种遍历方式都是基于递归实现的。 下面是一个使用递归实现 DFS 的示例代码(以二叉树为例): ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def dfs(self, node: TreeNode): if node is None: return print(node.val) # 先访问根节点 self.dfs(node.left) # 再遍历左子树 self.dfs(node.right) # 最后遍历右子树 def preorderTraversal(self, root: TreeNode) -> List[int]: self.result = [] self.dfs(root) return self.result ``` 在上面的代码中,我们定义了一个 TreeNode 类来表示二叉树中的节点,其中包括节点的值、左子节点和右子节点。我们还定义了一个 Solution 类来实现 DFS 遍历,其中 dfs() 方法用于进行深度优先遍历,preorderTraversal() 方法则是用于求解前序遍历的结果。在 dfs() 方法中,我们先访问根节点,然后再递归遍历左子树和右子树,直到遍历完整棵树。在遍历各个节点的过程中,我们可以将节点的值保存到一个列表中,最后返回即可。 当我们需要使用 DFS 遍历一棵树时,只需要创建一个 Solution 对象,然后调用其对应的方法即可。比如,可以使用如下代码来创建一棵二叉树,然后对其进行 DFS 遍历: ```python root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) solution = Solution() result = solution.preorderTraversal(root) print(result) # 输出: [1, 2, 4, 5, 3] ``` 在上面的代码中,我们首先创建了一棵二叉树,然后创建了一个 Solution 对象,最后调用其 preorderTraversal() 方法来进行遍历。遍历完成后,将遍历结果输出即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值