BFS相关题目
关于BFS的理论知识参考labuladong大佬的总结
https://labuladong.gitbook.io/algo/bi-du-wen-zhang/bfs-kuang-jia
BFS相关题目,一定要牢记一套代码框架,不同的题目基本都能通过套用框架解决:
int BFS(Node start, Node target) { queue<Node> que; unordered_set<Node> visited; // 记录已经遍历过的,避免走回头路 que.push(start); visited.insert(start); int step = 0; // 记录步数 while (!que.empty()) { int size = que.size(); for (int i = 0; i < size; i++) { Node node = que.front(); que.pop(); // 判断是否满足条件了,判断是否到达终点 if (node == target) { return step; } // 判断节点是否为空,并且是否已经遍历过 if (!node->left && visited.find(node->left) == visited.end()) { que.push(node->left); visited.insert(node->left); } if (!node->right && visited.find(node->right) == visited.end()) { que.push(node->right); visited.insert(node->right); } } step++; } return -1; // 没找到返回-1 }
class Solution { private: string plusOne(string s, int j) { if (s[j] == '9') { s[j] = '0'; } else { s[j] += 1; } return s; } string minusOne(string s, int j) { if (s[j] == '0') { s[j] = '9'; } else { s[j] -= 1; } return s; } public: int openLock(vector<string>& deadends, string target) { unordered_set<string> deads(deadends.begin(), deadends.end()); // 用集合来记录死亡数字,方便查找判断 unordered_set<string> visited; // 记录已经穷举过的密码 queue<string> que; que.push("0000"); visited.insert("0000"); int step = 0; while (!que.empty()) { int size = que.size(); for (int i = 0; i < size; i++) { string str = que.front(); que.pop(); if (deads.find(str) != deads.end()) { continue; } if (str == target) { return step; } for (int j = 0; j < 4; j++) { string up = plusOne(str, j); if (visited.find(up) == visited.end()) { que.push(up); visited.insert(up); } string down = minusOne(str, j); if (visited.find(down) == visited.end()) { que.push(down); visited.insert(down); } } } step++; } return -1; } };