欢迎使用CSDN-markdown编辑器

sicily1034

这是我第一次做深度优先查找的题目,感觉比广度优先查找,步骤简单的多。

 # include <iostream>
# include <queue>
# include <list> 
# include <algorithm>
# define MAX 100
# include <vector>
# include <cstring>
using namespace std;

bool visited[MAX];//用于判断每个节点是否被访问过 
vector<int> node[MAX];//保存每个节点所连接的节点 
bool noroot[MAX];//判断节点是否 不是根 
int max_depth = 0;
int max_width = 0;
int flag = true;
int width[MAX];//保存每个Level中的节点的数量 
void DFS(int cur,int depth = 0);//深度查找 
int main() {
    int N, M, i;

    while(true) {

        cin >> N >> M;

        if (N == 0) break;
        //初始化 

        queue<int> root;
        max_depth = max_width = 0;
        flag = true;
        memset(visited,false,sizeof(visited));
        memset(noroot,false,sizeof(noroot));
        memset(width,0,sizeof(width));

        if (M > N * N) flag = false;
        for (i = 0;i < N;i ++) {
            node[i].clear();
        }
        /// 
        for (i = 0;i < M;i ++) {
            int fir, sec;
            cin >> fir >> sec;
            node[fir - 1].push_back(sec - 1);
            if (fir != sec)
                noroot[sec - 1] = true;
        }
        for (i = 0;i < N;i ++) {
            if (!noroot[i])
                root.push(i);
        }

        //使最大宽度最初为根的个数 
        max_width = root.size();

        int size = root.size();
        if (root.size() == 0) flag = false;
        for (i = 0;i < size;i ++) {

            visited[root.front()] = true; 
            DFS(root.front(),0);
            root.pop();
        }

        if (flag) {
            for(i = 0;i <= max_depth;i ++) {
                if (max_width < width[i])
                    max_width = width[i];
            }
            cout << max_depth << " " << max_width <<  endl;
        }
        else {
            cout << "INVALID" << endl;
        }
    }
    return 0;
} 


void DFS(int cur,int depth) {
    if (!flag) return;
    if(depth > max_depth)
        max_depth = depth;


        width[depth + 1] += node[cur].size();

    if (node[cur].size() == 0)
        return;
    else {
        int i;
        for (i = 0;i < node[cur].size();i ++) {
            if (visited[node[cur][i]]) {
                flag = false;

                return;
            }
            else {
                visited[node[cur][i]] = true;
                DFS(node[cur][i],depth + 1);

            }
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值