BFS解开行李箱密码锁
题目:有一个带有四个圆形拨轮的转盘锁,每个拨轮都有0-9一共10个数字。每个拨轮可以上下旋转:例如把9变成0,或者0变成9,每次旋转只能将一个拨轮旋转一下。转盘锁的四个拨轮初始都是0,用字符串"0000"表示。现在给定输入一个列表deadends和一个字符串target,其中taeget代表可以打开密码锁的数字,而deadends中包含了一组死亡数字,要避免拨出其中的任何一个密码。请写出一个算法,计算从初始状态"0000"拨出target的最少次数,如果永远无法拨出target,则返回一个-1。
#include <iostream> #include <queue> #include <unordered_set> #include <string> using namespace std; class Solution { public: string plus_one(string str, int index)//str数组里面的第index个数据向上拨一下 { if (str[index] == '9') { str[index] = '0'; } else { str[index] = str[index] + 1; } return str; } string down_one(string str, int index) { if (str[index] == '0') { str[index] = '9'; } else { str[index] = str[index] - 1; } return str; } int openLock(vector<string>& deadends, string target) { int step = 0; unordered_set<string> deadset(deadends.begin(), deadends.end()); queue<string> lockQueue; lockQueue.push("0000"); unordered_set<string> visited; visited.insert("0000"); while (!lockQueue.empty()) { int sz = lockQueue.size(); for (int i = 0; i < sz; i++) { string node = lockQueue.front(); lockQueue.pop(); if (deadset.find(node) != deadset.end()) continue; if (node.compare(target) == 0)//如果遇到了直接返回步骤数目 return step; for (int j = 0; j < 4; j++) { string up = plus_one(node, j);//向上得到的结果 //如果这个结果不在visited里面就加入,同时放到队列 if (visited.count(up) <= 0) { visited.insert(up); lockQueue.push(up); } string down = down_one(node, j); if (visited.count(down) <= 0) { visited.insert(down); lockQueue.push(down); } } } step++; } return -1; } }; int main() { vector<string> dead = { "0201", "0101", "0102", "1212", "2002" }; string target("0202"); Solution s; int step = s.openLock(dead, target); cout << step << endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下