• DFS和WFS图


    #include <iostream>
    #include <vector>
    #include <string>
    #include <cstring>
    #include <queue>
    #include <stack>
    
    #define MAX 999
    using namespace std;
    int n;
    int map[MAX][MAX];
    bool vis[MAX];
    bool MapVis[MAX][MAX];
    
    void DFS()
    {
        for (int i = 0; i < n; ++i)
        {
            stack<int> s;
            s.push(i);
            memset(vis, 0, sizeof vis);
            memset(MapVis, 0, sizeof MapVis);
            while (!s.empty())
            {
                int x = s.top();
                s.pop();
                if (vis[x] == 0)
                {
                    cout << x << " ";
                    vis[x] = true;
                }
    
                for (int j = n - 1; j >= 0; j--)
                {
                    if (map[x][j] == 1 && MapVis[x][j] == 0)
                    {
                        s.push(j);
                        MapVis[x][j] = true;
                    }
                }
            }
            cout << endl;
        }
    }
    
    void WFS()
    {
        for (int i = 0; i < n; ++i)
        {
            queue<int> q;
            q.push(i);
            memset(vis, 0, sizeof vis);
            memset(MapVis, 0, sizeof MapVis);
            while (!q.empty())
            {
                int x = q.front();
                q.pop();
                if (vis[x] == 0)
                {
                    cout << x << " ";
                    vis[x] = true;
                }
    
                for (int j = 0; j < n; ++j)
                {
                    if (map[x][j] == 1 && MapVis[x][j] == 0)
                    {
                        q.push(j);
                        MapVis[x][j] = true;
                    }
                }
            }
            cout << endl;
        }
    }
    
    int main()
    {
        cin >> n;
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                cin >> map[i][j];
            }
        }
        cout << "DFS" << endl;
        DFS();
        cout << "WFS" << endl;
        WFS();
        return 0;
    }
  • 相关阅读:
    程序员如何利用空闲时间挣零花钱
    常见的数据交互之跳转页面传值
    一个能让cin和scanf 一样快的方法:
    HDU 4901 DP
    POJ 2823 线段树 Or 单调队列
    POJ 3264 线段树 ST
    POJ 3468 线段树+状压
    POJ 2777 线段树
    QQ 临时会话+图标 HTML代码
    POJ 1463 Strategic game
  • 原文地址:https://www.cnblogs.com/syzyaa/p/14140053.html
Copyright © 2020-2023  润新知