Depth-first search and breadth-first search of graphs

Source: Internet
Author: User

graph without Direction Depth-first search and breadth-first search


#include "stdafx.h" #include <vector> #include <iostream>using namespace std; #define N 9typedef Struct{int Vexnum, Arcnum;char vexs[n];int matirx[n][n];}   Graph;graph G;int A[n] = {0};//initialization graph Data//0---1---2---3---4---5---6---7---8---//a---B---C---D---E---F---g---H---I--- void Initiate_graph () {//A-B, a-d, a-eg.matirx[0][1] = 1;g.matirx[1][0] = 1;g.matirx[0][3] = 1;g.matirx[3][0] = 1;g.mati RX[0][4] = 1;g.matirx[4][0] = 1;//b-c g.matirx[1][2] = 1;g.matirx[2][1] = 1;//c-f g.matirx[2][5] = 1;g.matirx[5][2] = 1;//d-e, d-g g.matirx[3][4] = 1;g.matirx[4][3] = 1;g.matirx[3][6] = 1;g.matirx[6][3] = 1;//e-f, E-H g.matirx[4][5] = 1 ; G.matirx[5][4] = 1;g.matirx[4][7] = 1;g.matirx[7][4] = 1;//f-h, f-i g.matirx[5][7] = 1;g.matirx[7][5] = 1;g.matirx[5][8 ] = 1;g.matirx[8][5] = 1;//g-h g.matirx[6][7] = 1;g.matirx[7][6] = 1;//h-i g.matirx[7][8] = 1;g.matirx[8][7] = 1;} Depth-First search, recursive implementation void DFS (int k) {A[k] = 1;//marked as already accessed int mm = 0;while (mm < N) {if (g.matirx[k][mm] = = 1) {if (a[mm]! = 1) {cout << "[" << K << "]" << "[" << mm << "]" << endl;dfs (mm);}} mm++;}} void BFS () {Vector<int>vec;vector<int>aa;int k = 0;vec.push_back (0); a[0] = 1;while (Vec.size ()! = 0) {while (k < Vec.size ()) {cout << vec[k] << endl;int mm = 0;//a[vec[k]] = 1;while (mm < N) {if (g.matirx[vec[k]][mm] = = 1) {if (a[mm]! = 1) {aa.push_back (mm); a[mm] = 1;}} mm++;} k++;} VEC = Aa;k = 0;aa.clear ();}} int _tmain (int argc, _tchar* argv[]) {initiate_graph ();//dfs (0); BFS (); System ("pause"); return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Depth-first search and breadth-first search of graphs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.