• 回溯算法---Backtracking Algorithm


     本篇主要是介绍一下回溯算法:所谓回溯算法,又称为“试探法”。解决问题时,每进行一步,都是抱着试试看的态度,如果发现当前选择并不是最好的,或者这么走下去肯定达不到目标,立刻做回退操作重新选择。这种走不通就回退再走的方法就是回溯算法。
     


     

     

    文章目录

    • 一、回溯算法的定义
    • 二、回溯算法的模型
      • 深度优先搜索
      • 广度优先搜索
    • 三、有关回溯算法的题型

     

    一、回溯算法的定义

    回溯法:实际上回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径

    回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足条件的某个状态的点称为“回溯点”。也可以称为剪枝点,所谓的剪枝,指的是把不会找到的目标,或者不必要的路径裁减掉。

    在包含问题的所有解中空间树中,按照深度优先搜索的策略,从根结点出发深度探索解空间树。当深度到某一结点时,要先判断该结点是否包含问题的解,如果包含,就从该结点出发探索下去,如果该结点不包含问题的解,则逐层向其祖先结点回溯。(其实回溯法就是对隐式图的深度优先搜索算法)。

    如果使用回溯法求解问题的时候,要回溯到根,且根结点的所有可行的子树都要已被搜索遍才结束。

    而若使用回溯法求任一解时,只要搜索到问题的一个解就可以结束。(除了深度优先搜索外,常见的还有广度优先搜索)。

    二、回溯算法的模型

    一、深度优先遍历(DFS)

    DFS(当前这一步的处理逻辑)
    {
    1. 判断边界,是否已经一条道走到黑了:向上回退
    2. 尝试当下的每一种可能
    3. 确定一种可能之后,继续下一步 DFS(下一步)
    }

    二、广度优先遍历(BFS)

    BFS()
    {
    1. 建立起始步骤,队列初始化
    2. 遍历队列中的每一种可能,whlie(队列不为空)
    {
    通过队头元素带出下一步的所有可能,并且依次入队
    {
    判断当前情况是否达成目标:按照目标要求处理逻辑
    }
    继续遍历队列中的剩余情况
    }
    }

    三、有关回溯算法的题型

    一、有关深度优先遍历的题型

    1.员工的重要性OJ链接

    1. /*
    2. // Definition for Employee.
    3. class Employee {
    4. public:
    5. int id;
    6. int importance;
    7. vector subordinates;
    8. };
    9. */
    10. class Solution {
    11. public:
    12. int DFS(unordered_map<int,Employee*>&info,int id)
    13. {
    14. int sumImportance=info[id]->importance;
    15. //深度探索员工一的下属然后往下探索员工二的下属……
    16. for(auto e:info[id]->subordinates)
    17. {
    18. sumImportance+=DFS(info,e);
    19. }
    20. //最后返回员工的数据结构中的重要度的和
    21. return sumImportance;
    22. }
    23. int getImportance(vector employees, int id) {
    24. //如果此时没有保存员工的数据结构则返回空的重要度
    25. if(employees.empty())
    26. return 0;
    27. //为了使时间效率更高可以使用哈希的结构,因为哈希的查找效率比较高
    28. unordered_map<int,Employee*> info;
    29. //将员工的信息的数据结构放入哈希表中
    30. for(auto e:employees)
    31. {
    32. info[e->id]=e;
    33. }
    34. return DFS(info,id);//将哈希表中的内容进行深度优先搜索操作
    35. }
    36. };

    2.图像渲染OJ链接

    1. int nextp[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
    2. class Solution {
    3. public:
    4. void DFS(vectorint>>&image,vectorint>>&book,int row,int col,int sr,int sc,int oldColor,int newColor)
    5. {
    6. image[sr][sc]=newColor;
    7. book[sr][sc]=1;
    8. for(int i=0;i<4;i++)
    9. {
    10. int newX=sr+nextp[i][0];
    11. int newY=sc+nextp[i][1];
    12. if(newX>=row||newX<0)
    13. {
    14. continue;
    15. }
    16. if(newY>=col||newY<0)
    17. {
    18. continue;
    19. }
    20. if(image[newX][newY]==oldColor&&book[newX][newY]==0)
    21. {
    22. DFS(image,book,row,col,newX,newY,oldColor,newColor);
    23. }
    24. }
    25. }
    26. vectorint>> floodFill(vectorint>>& image, int sr, int sc, int color) {
    27. if(image.empty())
    28. {
    29. return image;
    30. }
    31. vectorint>> book(image.size(),vector<int>(image[0].size(),0));
    32. int oldColor=image[sr][sc];
    33. DFS(image,book,image.size(),image[0].size(),sr,sc,oldColor,color);
    34. return image;
    35. }
    36. };

    3.岛屿的周长OJ链接

    1. int nextp[4][2]={{1,0},{0,1},{-1,0},{0,-1}};//给定方向矩阵
    2. class Solution {
    3. public:
    4. int DFS(vectorint>> &grid,int row,int col,int x,int y)
    5. {
    6. if(x>=row||x<0||y>=col||y<0||grid[x][y]==0) return 1;
    7. if(grid[x][y]==2) return 0;
    8. grid[x][y]=2;//标记此时位置已经搜索过
    9. int s=0;
    10. //对于此时的位置进行深度优先遍历操作
    11. for(int k=0;k<4;k++)
    12. {
    13. int newX=x+nextp[k][0];
    14. int newY=y+nextp[k][1];
    15. //对于该位置进行深度优先遍历求出此时的位置有效的边界长度
    16. s+=DFS(grid,row,col,newX,newY);
    17. }
    18. return s;
    19. }
    20. int islandPerimeter(vectorint>>& grid) {
    21. if(grid.empty())
    22. return 0;
    23. int row=grid.size();
    24. int col=grid[0].size();
    25. int c=0;
    26. for(int i=0;i
    27. {
    28. for(int j=0;j
    29. {
    30. //对于陆地进行深度优先遍历操作
    31. if(grid[i][j]==1)
    32. c+=DFS(grid,row,col,i,j);
    33. }
    34. }
    35. return c;
    36. }
    37. };

    4.被围绕的区域OJ链接

    1. int nextp[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
    2. class Solution {
    3. public:
    4. void DFS(vectorchar>>&board,int row,int col,int sr,int sc)
    5. {
    6. board[sr][sc]='*';//标记此时为‘O’深度探索是否被
    7. for(int i=0;i<4;i++)
    8. {
    9. int newX=sr+nextp[i][0];//将此时的方向进行四个方向进行深度优先遍历操作
    10. int newY=sc+nextp[i][1];
    11. if(newX<0||newX>=row)//需要对此时的方向进行判断是否是越界行为,如果是越界行为则此时跳过去,进行下一个方向的深度优先遍历操作
    12. {
    13. continue;
    14. }
    15. if(newY<0||newY>=col)
    16. {
    17. continue;
    18. }
    19. if(board[newX][newY]!='*'&&board[newX][newY]!='X')//
    20. //继续搜索‘O’
    21. {
    22. DFS(board,row,col,newX,newY);
    23. }
    24. }
    25. }
    26. void solve(vectorchar>>& board) {
    27. if(board.empty())
    28. return;
    29. int row=board.size();
    30. int col=board[0].size();
    31. //第一行和最后一行进行深度优先遍历
    32. for(int j=0;j
    33. {
    34. if(board[0][j]=='O')
    35. DFS(board,row,col,0,j);
    36. if(board[row-1][j]=='O')
    37. DFS(board,row,col,row-1,j);
    38. }
    39. //第一列和最后一列进行深度优先遍历
    40. for(int i=0;i
    41. {
    42. if(board[i][0]=='O')
    43. DFS(board,row,col,i,0);
    44. if(board[i][col-1]=='O')
    45. DFS(board,row,col,i,col-1);
    46. }
    47. //最后将深度搜索的结果进行修改
    48. for(int i=0;i
    49. {
    50. for(int j=0;j
    51. {
    52. if(board[i][j]=='*')//最后将所有的'*'改为‘O’
    53. {
    54. board[i][j]='O';
    55. }
    56. else if(board[i][j]=='O')//最后将所有的'O'改为‘X’
    57. {
    58. board[i][j]='X';
    59. }
    60. }
    61. }
    62. }
    63. };

    5.岛屿数量OJ链接

    1. int nextp[4][2]={{1,0},{0,1},{-1,0},{0,-1}};//定义一个方向矩阵
    2. class Solution {
    3. public:
    4. void DFS(vectorchar>>&grid,vectorint>>&book,int row,int col,int x,int y)
    5. {
    6. book[x][y]=1;//标记此时的位置已经走过
    7. for(int k=0;k<4;k++)//对于当前x,y的位置进行方向遍历操作
    8. {
    9. int newX=x+nextp[k][0];//对于x的横向坐标
    10. int newY=y+nextp[k][1];//对于y的纵向坐标
    11. if(newX>=row||newX<0||newY>=col||newY<0)//考虑一下边界的问题,如果此时走到了边界应该访问下一个位置
    12. continue;
    13. if(grid[newX][newY]=='1'&&book[newX][newY]==0)
    14. DFS(grid,book,row,col,newX,newY);
    15. }
    16. }
    17. int numIslands(vectorchar>>& grid) {
    18. if(grid.empty())
    19. return 0;
    20. int row=grid.size();
    21. int col=grid[0].size();
    22. //标记矩阵
    23. vectorint>> book(row,vector<int>(col,0));
    24. int amount=0;
    25. for(int i=0;i
    26. for(int j=0;j
    27. if(grid[i][j]=='1'&&book[i][j]==0)
    28. {
    29. amount++;
    30. DFS(grid,book,row,col,i,j);
    31. }
    32. return amount;
    33. }
    34. };

     

    6.岛屿的最大面积OJ链接

    1. int nextp[4][2]={{1,0},{0,1},{-1,0},{0,-1}};//给定方向矩阵
    2. int s=0;//定义全局变量来求出每个岛屿的面积
    3. class Solution {
    4. public:
    5. void DFS(vectorint>>&grid,int row,int col,int x,int y)
    6. {
    7. //如果此时为陆地则进行S++
    8. if(grid[x][y]==1)
    9. s++;
    10. grid[x][y]=2;//同时标记此时已经走过
    11. for(int k=0;k<4;k++)//从当前位置进行方向遍历
    12. {
    13. int newX=x+nextp[k][0];
    14. int newY=y+nextp[k][1];
    15. if(newX<0||newX>=row||newY<0||newY>=col)
    16. continue;
    17. if(grid[newX][newY]==1)//从陆地开始进行深度遍历
    18. DFS(grid,row,col,newX,newY);
    19. }
    20. }
    21. int maxAreaOfIsland(vectorint>>& grid) {
    22. if(grid.empty())
    23. return 0;
    24. int row=grid.size();
    25. int col=grid[0].size();
    26. int maxS=0;
    27. for(int i=0;i
    28. for(int j=0;j
    29. if(grid[i][j]==1)//从陆地开始进行深度优先遍历操作
    30. //将每一个位置进行比较,找出最大那个岛屿的面积
    31. {
    32. DFS(grid,row,col,i,j);
    33. maxS=max(maxS,s);
    34. s=0;
    35. }
    36. return maxS;
    37. }
    38. };

     

    7.电话号码的字母组合OJ链接

    1. map<char,string> hashTable={{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
    2. class Solution {
    3. public:
    4. void DFS(string& digits,vector&resultString,string curStr,int curDepth)
    5. {
    6. //如果此时遍历到最后一个
    7. if(curDepth==digits.size())
    8. {
    9. resultString.push_back(curStr);
    10. return;
    11. }
    12. //利用哈希映射的方式进行
    13. string strMap=hashTable[digits[curDepth]];
    14. for(char ch:strMap)
    15. {
    16. DFS(digits,resultString,curStr+ch,curDepth+1);
    17. }
    18. }
    19. vector letterCombinations(string digits) {
    20. //将所有的结果集保存到resultString
    21. vector resultString;
    22. if(digits.empty())
    23. return resultString;
    24. //从第一个位置开始进行深度优先遍历深度优先遍历
    25. DFS(digits,resultString,"",0);
    26. return resultString;
    27. }
    28. };

     

    8.组合总和OJ链接

    1. class Solution {
    2. public:
    3. void DFS(vector<int>&candidates,vectorint>>&solutions,vector<int>&solution,int curSum,int position,int target)
    4. {
    5. //如果当前遍历所得到的结果刚好为所给的target值
    6. //那么将当前所遍历的结果集保留在solutions
    7. if(curSum==target)
    8. {
    9. solutions.push_back(solution);
    10. }
    11. //如果遍历出的和是大于,则说明此时条件不满足
    12. if(curSum>target)
    13. {
    14. return;
    15. }
    16. //从position位置开始进行深度优先遍历操作
    17. for(int i=position;isize();i++)
    18. {
    19. if(candidates[i]>target)//如果此时的所给出的candidats中
    20. // //的值比所给的target大,那么直接结束当前所在位置的优先遍历
    21. {
    22. continue;
    23. }
    24. //不满足上述条件说明此时的curSum的值小于target
    25. //可以将当前的candidates[i]放入到当前的结果集中
    26. //然后接着往后进行深度优先遍历操作
    27. solution.push_back(candidates[i]);
    28. DFS(candidates,solutions,solution,curSum+candidates[i],i,target);
    29. solution.pop_back();
    30. }
    31. }
    32. vectorint>> combinationSum(vector<int>& candidates, int target) {
    33. //定义一个二维数组保留所有结果集
    34. vectorint>> solutions;
    35. //保留当前的结果集
    36. vector<int> solution;
    37. //记录当前结果集中的和
    38. int curSum=0;
    39. //进行深度优先遍历
    40. DFS(candidates,solutions,solution,curSum,0,target);
    41. return solutions;
    42. }
    43. };

    9.活字印刷OJ链接

    1. class Solution {
    2. public:
    3. void DFS(string &tiles,string curStr,vector<int>&useString,unordered_set&hashTable)
    4. {
    5. //如果此时深度优先遍历的字符串不为空,则此时的所得到的的字符串放入当前的哈希表中,将自动进行去重的处理
    6. if(!curStr.empty())
    7. hashTable.insert(curStr);
    8. //深度优先遍历每一个位置
    9. for(int i=0;isize();i++)
    10. {
    11. if(useString[i])//如果当前的位置已经被访问过,则说明此时当前位置不需要访问
    12. continue;
    13. useString[i]=1;//标记当前位置
    14. DFS(tiles,curStr+tiles[i],useString,hashTable);//继续往下进行深度优先遍历的操作
    15. //需要进行回退的操作
    16. useString[i]=0;
    17. }
    18. }
    19. int numTilePossibilities(string tiles) {
    20. if(tiles.empty())
    21. return 0;
    22. //利用unoreded_set容器的特性,将容器内的内容自动进行去重操作
    23. unordered_set hashTable;
    24. //先将当前的tiles进行初始化的操作
    25. vector<int> useString(tiles.size(),0);
    26. //进行深度优先遍历操作
    27. DFS(tiles,"",useString,hashTable);
    28. return hashTable.size();
    29. }
    30. };

     

    10.N皇后OJ链接

    1. class Solution {
    2. public:
    3. //深度优先遍历
    4. void DFS(vectorint,int>>>&solutions,vectorint,int>>&solution,int curRow,int n)
    5. {
    6. //如果当前行等于n则将一种solution方案放入solutions中
    7. if(curRow==n)
    8. {
    9. solutions.push_back(solution);
    10. }
    11. for(int i=0;i
    12. {
    13. //判断当前皇后所在的位置是否能够满足条件
    14. if(isValid(solution,curRow,i))
    15. {
    16. //如果满足条件则将此时的坐标记录下来
    17. solution.push_back(make_pair(curRow,i));
    18. //继续深度优先遍历下一行
    19. DFS(solutions,solution,curRow+1,n);
    20. //第一列遍历后回溯下来遍历第二行
    21. solution.pop_back();
    22. }
    23. }
    24. }
    25. bool isValid(vectorint,int>>&solution,int curRow,int col)
    26. {
    27. //遍历方案中的点
    28. //如果此时该皇后中的纵坐标与方案中的纵坐标相同或者横坐标与纵坐标的和等于当前皇后的横纵坐标之和或者是方案中横纵坐标之差等于当前皇后的横纵坐标之差
    29. for(auto i:solution)
    30. {
    31. if(i.second==col||i.first+i.second==curRow+col||i.first-i.second==curRow-col)
    32. {
    33. return false;
    34. }
    35. }
    36. return true;
    37. }
    38. vector> transformString(vectorint,int>>>&solutions,int n)
    39. {
    40. vector> resultString;//保留最后方案中的字符串
    41. for(vectorint,int>>&solution:solutions)
    42. {
    43. //利用构造函数先进行所有的字符变为'.'最后再将皇后位置变为'Q'
    44. vector tmpString(n,string(n,'.'));
    45. for(pair<int,int> &i:solution)
    46. {
    47. tmpString[i.first][i.second]='Q';
    48. }
    49. resultString.push_back(tmpString);
    50. }
    51. return resultString;
    52. }
    53. vector> solveNQueens(int n) {
    54. vectorint,int>>> solutions;//将不同解法的方案存放
    55. vectorint,int>> solution;//存放一种方案中的n个皇后的摆放
    56. //将n*n的棋盘从第一个位置开始进行深度优先遍历
    57. DFS(solutions,solution,0,n);
    58. //将深度优先遍历后的每一种方案都转化为字符型
    59. return transformString(solutions,n);
    60. }
    61. };

    11.N皇后IIOJ链接

    1. class Solution {
    2. public:
    3. //深度优先遍历
    4. int DFS(vectorint,int>>&solution,int curRow,int n)
    5. {
    6. //如果当前行等于n则将一种solution
    7. if(curRow==n)
    8. {
    9. return 1;
    10. }
    11. else
    12. {
    13. int count=0;
    14. for(int i=0;i
    15. {
    16. //判断当前皇后所在的位置是否能够满足条件
    17. if(isValid(solution,curRow,i))
    18. {
    19. //如果满足条件则将此时的坐标记录下来
    20. solution.push_back(make_pair(curRow,i));
    21. //继续深度优先遍历下一行
    22. count+=DFS(solution,curRow+1,n);
    23. //第一列遍历后回溯下来遍历第二行
    24. solution.pop_back();
    25. }
    26. }
    27. return count;
    28. }
    29. }
    30. bool isValid(vectorint,int>>&solution,int curRow,int col)
    31. {
    32. //遍历方案中的点
    33. //如果此时该皇后中的纵坐标与方案中的纵坐标相同或者横坐标与纵坐标的和等于当前皇后的横纵坐标之和或者是方案中横纵坐标之差等于当前皇后的横纵坐标之差
    34. for(auto i:solution)
    35. {
    36. if(i.second==col||i.first+i.second==curRow+col||i.first-i.second==curRow-col)
    37. {
    38. return false;
    39. }
    40. }
    41. return true;
    42. }
    43. int totalNQueens(int n) {
    44. vectorint,int>> solution;
    45. return DFS(solution,0,n);
    46. }
    47. };

    二、有关广度优先遍历的题型

    1.N叉树的层序遍历OJ链接

    1. /*
    2. // Definition for a Node.
    3. class Node {
    4. public:
    5. int val;
    6. vector children;
    7. Node() {}
    8. Node(int _val) {
    9. val = _val;
    10. }
    11. Node(int _val, vector _children) {
    12. val = _val;
    13. children = _children;
    14. }
    15. };
    16. */
    17. class Solution {
    18. public:
    19. vectorint>> levelOrder(Node* root) {
    20. if(root==nullptr) return vectorint>>();
    21. vectorint>> vv;
    22. queue q;//利用队列进行广度优先遍历
    23. q.push(root);//首先将头结点先入队操作
    24. while(!q.empty())//如果此时的队列不为空,则继续进行操作
    25. {
    26. vector<int> v;//利用一个一维数组来存储当前层的节点
    27. int size=q.size();//每一层的大小需要保存下来,方便下一次的遍历操作
    28. for(int i=0;i
    29. {
    30. Node*front=q.front();
    31. q.pop();
    32. v.push_back(front->val);
    33. for(auto child:front->children)//遍历当前节点的孩子节点,如果不为空,则将此时的孩子节点入队列
    34. if(child)
    35. q.push(child);
    36. }
    37. vv.push_back(v);
    38. }
    39. return vv;
    40. }
    41. };

     

    2.腐烂的橘子OJ链接

    1. int nextp[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
    2. class Solution {
    3. public:
    4. int orangesRotting(vectorint>>& grid) {
    5. //利用pair来存储位置信息
    6. queueint,int>> q;
    7. int row=grid.size();
    8. int col=grid[0].size();
    9. //第一步将腐烂的橘子进行入队操作
    10. for(int i=0;i
    11. for(int j=0;j
    12. if(grid[i][j]==2)
    13. q.push(make_pair(i,j));
    14. //进行蔓延的方向
    15. int times=0;
    16. while(!q.empty()){
    17. int size=q.size();
    18. int flag=0;//定义一个flag来判断是否是有新橘子被腐烂
    19. for(int i=0;i
    20. pair<int,int> Curpos=q.front();
    21. q.pop();
    22. for(int i=0;i<4;i++){
    23. int newX=Curpos.first+nextp[i][0];
    24. int newY=Curpos.second+nextp[i][1];
    25. //如果此时的位置中存在越界或者是该位置上面的橘子已经被腐烂过则跳过此次
    26. if(newX>=row||newY>=col||newX<0||newY<0||grid[newX][newY]!=1)
    27. continue;
    28. flag=1;
    29. grid[newX][newY]=2;
    30. q.push(make_pair(newX,newY));
    31. }
    32. }
    33. if(flag)
    34. ++times;
    35. }
    36. //最后需要进行判断是否还存在无法腐烂的橘子
    37. for(int i=0;i
    38. for(int j=0;j
    39. if(grid[i][j]==1)
    40. return -1;
    41. return times;
    42. }
    43. };

    3.单词接龙OJ链接

    1. class Solution {
    2. public:
    3. int ladderLength(string beginWord, string endWord, vector& wordList) {
    4. //利用哈希表进行查找效率比较高
    5. unordered_set HashTable(wordList.begin(),wordList.end());
    6. //定义一个标记的哈希表来标记已经查找过的单词
    7. unordered_set visitHashTable;
    8. //讲起始的单词进行标记
    9. visitHashTable.insert(beginWord);
    10. //利用队列的特性进行广度优先遍历操作
    11. queue q;
    12. q.push(beginWord);
    13. int step=1;
    14. //队列不为空,继续进行转换操作
    15. while(!q.empty())
    16. {
    17. int size=q.size();
    18. for(int i=0;i
    19. {
    20. //用来保存队列中第一个单词进行转换操作
    21. string curWord=q.front();
    22. q.pop();
    23. for(int i=0;isize();i++){
    24. //对于当前单词进行转换操作
    25. string newWord=curWord;
    26. for(char ch='a';ch<='z';ch++)
    27. {
    28. //替换newWord中的字符来进行转换
    29. newWord[i]=ch;
    30. //如果此时的单词在哈希表中没有找到,或者该单词已经被标记过
    31. if(!HashTable.count(newWord)||visitHashTable.count(newWord))
    32. continue;
    33. if(newWord==endWord)
    34. return step+1;
    35. //如果没有转换成功,需要进行入队操作和进行标记操作
    36. q.push(newWord);
    37. visitHashTable.insert(newWord);
    38. }
    39. }
    40. }
    41. step++;
    42. }
    43. return 0;
    44. }
    45. };

    4.最小基因变化OJ链接

    1. class Solution {
    2. public:
    3. int minMutation(string startGene, string endGene, vector& bank) {
    4. //利用哈希表查找
    5. unordered_set HashTable(bank.begin(),bank.end());
    6. //标记
    7. unordered_set visitHashTable;
    8. visitHashTable.insert(startGene);
    9. //利用队列进行广度优先遍历操作
    10. queue q;
    11. q.push(startGene);
    12. //对于基因有四种可能
    13. vector<char> Gene(4);
    14. Gene[0]='A';
    15. Gene[1]='C';
    16. Gene[2]='G';
    17. Gene[3]='T';
    18. int step=0;
    19. while(!q.empty())
    20. {
    21. int size=q.size();
    22. for(int i=0;i
    23. {
    24. string curGene=q.front();
    25. q.pop();
    26. //对于当前基因的位置进行广度遍历
    27. for(int j=0;jsize();j++)
    28. {
    29. string newGene=curGene;
    30. for(auto ch:Gene)
    31. {
    32. newGene[j]=ch;
    33. //如果已经出现了当前的基因或者是该基因不存在
    34. if(!HashTable.count(newGene)||visitHashTable.count(newGene))
    35. continue;
    36. //如果此时的基因正好是等于当前的基因
    37. if(newGene==endGene)
    38. return step+1;
    39. //否则讲当前额的基因入队列
    40. visitHashTable.insert(newGene);
    41. q.push(newGene);
    42. }
    43. }
    44. }
    45. step++;
    46. }
    47. return -1;
    48. }
    49. };

    5.打开转盘锁 OJ链接

    1. class Solution {
    2. public:
    3. int openLock(vector& deadends, string target) {
    4. //利用哈希表的查找
    5. unordered_set HashTable(deadends.begin(),deadends.end());
    6. if(HashTable.find("0000")!=HashTable.end())
    7. return -1;
    8. //标记已经搜索过的字符串
    9. unordered_set visitHashTable;
    10. visitHashTable.insert("0000");
    11. //利用队列进行广度优先遍历
    12. queue q;
    13. q.push("0000");
    14. int step=0;
    15. while(!q.empty())
    16. {
    17. int size=q.size();
    18. for(int i=0;i
    19. {
    20. string curString=q.front();
    21. q.pop();
    22. //如果此时curStringw为目标则直接返回
    23. if(curString==target)
    24. return step;
    25. for(int j=0;jsize();j++)
    26. {
    27. string newString1=curString;
    28. string newString2=curString;
    29. //当前位置可以向前或者向后拨动
    30. newString1[j]=newString1[j]=='9'?'0':newString1[j]+1;
    31. newString2[j]=newString2[j]=='0'?'9':newString2[j]-1;
    32. if(HashTable.find(newString1)==HashTable.end()&&visitHashTable.find(newString1)==visitHashTable.end())
    33. {
    34. q.push(newString1);
    35. visitHashTable.insert(newString1);
    36. }
    37. if(HashTable.find(newString2)==HashTable.end()&&visitHashTable.find(newString2)==visitHashTable.end())
    38. {
    39. q.push(newString2);
    40. visitHashTable.insert(newString2);
    41. }
    42. }
    43. }
    44. step++;
    45. }
    46. return -1;
    47. }
    48. };

     

     

  • 相关阅读:
    24届好未来数开笔试
    SpringMVC之综合案例:参数传递,向页面传参,页面跳转
    【FAQ】安防视频监控平台EasyNVR无法控制云台,该如何解决?
    React知识点系列(5)-每天10个小知识
    数商云SCM系统实时订单协同与信息共享推动家居建材企业数字化转型
    【ArcGIS风暴】CASS建立标准分幅图框并在ArcGIS中DOM批量分幅案例教程
    WebGIS----前端(二)
    Linux基础知识与实操-篇七:用户身份切换与特殊控制
    毕业设计--基于SSM实现的的校园订餐系统源码+数据库
    2023 IDC中国数字金融论坛丨中电金信向行业分享“源启+应用重构”新范式
  • 原文地址:https://blog.csdn.net/qq_67458830/article/details/127712673