bfs/dfs(邻接矩阵)

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
#define V 3000
#define E 10000
int map[V][V];
int vis[V];
int n,m,st,end;
int queue[V];
void dfs(int u)
{
    vis[u]=1;
    for(int i=1;i<=n;i++)
    {
        if(vis[i]==0 && map[u][i]==1)
        {
            dfs(i);
            //vis[i]=2;
        }
    }
}
void bfs(int u)
{
    vis[u]=1;
    int v,head=0,tail=0;
    queue[tail++]=u;
    while(head<tail)
    {
        v=queue[head++];
        for(int i=1;i<=n;i++)
        {
            if(map[v][i]==1 && vis[i]==0)
            {
                vis[i]=1;
                queue[tail++]=i;
                if(i==end) return ;
            }
        }
    }
}
int main()
{
    int a,b;
    while(cin >> n >> m >> st >> end)
    {
        memset(map,0,sizeof(map));
        for(int i=0;i<m;i++)
        {
            cin >> a >> b;
            map[a][b]=1;
        }
        dfs(st);

        for(int i=1;i<=n;i++)
        {
            cout << vis[i] << " ";
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/markliu/p/2495932.html