关于广度优先搜索bfs
发布日期:2021-05-15 07:31:19 浏览次数:15 分类:精选文章

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

���������������������BFS���������������������������������������������������������������������������������������������BFS���������������������������������������������������������������������������

���������������������

������������������������������������9������������������������������������0������������������������������������������������������������������������012345678������������������������087654321���������������������������������

������������

������������������������������������������

  • ������������������������������������������������������
  • ������������������������������������������������������������������������������
  • ���������������������������������������������������������������������������������

    BFS������������

  • ���������������������������������������������������������������
  • ���������������������������������������������������������������
  • ������������������������������������������������
  • ���������������������������������������������������������������
  • ������������

    #include 
    #include
    #include
    #include
    #include
    #include
    #include
    using namespace std; struct node { string str; int pos; int step; node(string s, int p, int step) : str(s), pos(p), step(step) {} }; int main() { string start = "012345678"; string target = "087654321"; queue
    q; set
    visited; node first(start, 0, 0); q.push(first); visited.insert(start); while (!q.empty()) { node temp = q.front(); q.pop(); if (temp.str == target) { return temp.step; } int current_pos = temp.pos; int current_str = current_pos; // ��������������������������������� for (int move : {-1, 1, -2, 2}) { int new_pos = (current_pos + move + 9) % 9; string new_str = temp.str; swap(new_str[new_pos], new_str[current_pos]); if (new_str == start && move != 0) { // ������������������ // skip } else if (new_str != temp.str) { if (visited.find(new_str) == visited.end()) { node nextNode(new_str, new_pos, temp.step + 1); q.push(nextNode); if (new_str == target) { return temp.step + 1; } visited.insert(new_str); } } } } return 0; }

    ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

    上一篇:[蓝桥杯2018初赛]测试次数
    下一篇:[蓝桥杯2017初赛]迷宫

    发表评论

    最新留言

    哈哈,博客排版真的漂亮呢~
    [***.90.31.176]2025年05月02日 19时04分21秒