博客
关于我
数据结构实验之图论五:从起始点到目标点的最短步数(BFS)
阅读量:617 次
发布时间:2019-03-12

本文共 1185 字,大约阅读时间需要 3 分钟。

????????????????1????n????????????????????????BFS???????BFS??????????????

????

  • ??????????1?????n??????????????????????????????BFS???????
  • ??????????????????????????????
  • ???????BFS??????1???????????????????n?????BFS????????????????
  • ???????????????????????BFS???????????????
  • ????

    #include 
    #include
    #include
    using namespace std;int main() { int k; // ?????? cin >> k; for (int test = 0; test < k; ++test) { int n, m; cin >> n >> m; vector
    > graph(n + 1); vector
    distance(n + 1, -1); queue
    q; distance[1] = 0; q.push(1); bool found = false; while (!q.empty()) { int u = q.front(); q.pop(); for (int v : graph[u]) { if (distance[v] == -1) { distance[v] = distance[u] + 1; if (v == n) { found = true; break; } q.push(v); } } if (found) break; } if (distance[n] == -1) { cout << "NO" << endl; } else { cout << distance[n] << endl; } } return 0;}

    ????

  • ???????????????????????????
  • ???????????????graph???????????????distance????????????
  • BFS????1???????????????n?????????
  • ?????????n???????????????NO?
  • ??????????????????????????????

    转载地址:http://pkexz.baihongyu.com/

    你可能感兴趣的文章
    Python-【1】配置
    查看>>
    Python-从子文件夹执行绝对导入
    查看>>
    Python-刷新页面,直到元素可单击
    查看>>
    PYTHON-唤醒+VOSK+DEEPSEEK+离线合成-实现纯离线大模型问答
    查看>>
    Python-在Dash回调中重用函数
    查看>>