深度遍历:顶点A->A的第一个邻接顶点->......
广度遍历:顶点A->A的所有邻接顶点->A的第一个邻接顶点的所有未使用过的邻接顶点
BFS(广度遍历)类似于树的层次遍历,同样借用与队列,把顶点A放入队列,把A出队用front存下A,把A的邻接顶点全部入队并标记。
BFS代码如下:
void GraphLink::BFS(char v) { int p = GetVertexIndex(v); if (p == -1) return; bool* visited = new bool[m_NumVertex];//标记数组 for (int i = 0; i < m_NumVertex; i++) { visited[i] = false;//全部赋值为false } queue<int> qq; qq.push(p);//顶点下标进行入队 visited[p] = true;//入队了的下标,标记为true cout << (char)v << " ";//打印 int front; Edge* plist =nullptr; while (!qq.empty()) { front = qq.front(); qq.pop(); plist = m_VerArr[front].m_list;//plist指向A的邻接表 while (plist!=nullptr)//邻接表不为空 { if (!visited[plist->m_destindex])//邻接表没被用过 { cout << (char)m_VerArr[plist->m_destindex].m_VerValue << " "; visited[plist->m_destindex] = true;//标记 qq.push(plist->m_destindex);//入队 } plist = plist->m_next;邻接表第一个顶点用过,访问下一个顶点 } } }
运行结果:
深度遍历(DFS):先写一个bool*visited标记数组每个顶点都初始为false,使用递归深度遍历顶点的第一个顶点,第一个顶点邻接表的第一个顶点,如果这个邻接表的第一个顶点被标记过,找他的下一个顶点。
代码如下:
void GraphLink::DFS(int v, bool* visited)//递归深度遍历 { cout << (char)m_VerArr[v].m_VerValue << " "; visited[v] = true; Edge* p = m_VerArr[v].m_list; while (p != nullptr) {//从没有被使用过的顶点开始 if (!visited[p->m_destindex]) { DFS(p->m_destindex, visited); } p = p->m_next; } } void GraphLink::DFS(char v)//创造一个标记数组,标记数组不参与递归 { int p = GetVertexIndex(v); if (p == -1) return; bool* visited = new bool[m_NumVertex]; for (int i = 0; i < m_NumVertex; i++) { visited[i] = false; } DFS(p, visited); delete[]visited; visited = nullptr; }
运行结果:
图的两种遍历方式:深度遍历DFS和广度遍历BFS
本文介绍了图的两种遍历方法:BFS(广度优先搜索)和DFS(深度优先搜索)。BFS利用队列进行层次遍历,而DFS采用递归方式遍历。文中提供了C++实现的BFS和DFS代码示例,用于遍历图中的顶点并避免重复访问。
摘要由CSDN通过智能技术生成