欢迎使用CSDN-markdown编辑器

来源:互联网 发布:有经商软件吗 编辑:程序博客网 时间:2024/06/16 06:11

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);            }        }    }}
0 0
原创粉丝点击