算法-回溯

📅 2026/7/20 13:14:31 👁️ 阅读次数 📝 编程学习
算法-回溯

通用模板

/* 回溯算法框架 */voidbacktrack(Statestate,List<Choice>choices,List<State>res){// 判断是否为解if(isSolution(state)){// 记录解recordSolution(state,res);// 不再继续搜索return;}// 遍历所有选择for(Choicechoice:choices){// 剪枝:判断选择是否合法if(isValid(state,choice)){// 尝试:做出选择,更新状态makeChoice(state,choice);backtrack(state,choices,res);// 回退:撤销选择,恢复到之前的状态undoChoice(state,choice);}}}

与图深度优先搜索对比:

/* 深度优先遍历辅助函数 */voiddfs(GraphAdjListgraph,Set<Vertex>visited,List<Vertex>res,Vertexvet){res.add(vet);// 记录访问顶点visited.add(vet);// 标记该顶点已被访问// 遍历该顶点的所有邻接顶点for(VertexadjVet:graph.adjList.get(vet)){if(visited.contains(adjVet))continue;// 跳过已被访问的顶点// 递归访问邻接顶点dfs(graph,visited,res,adjVet);}}/* 深度优先遍历 */// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点List<Vertex>graphDFS(GraphAdjListgraph,VertexstartVet){// 顶点遍历序列List<Vertex>res=newArrayList<>();// 哈希集合,用于记录已被访问过的顶点Set<Vertex>visited=newHashSet<>();dfs(graph,visited,res,startVet);returnres;}

图的宽度优先搜索:

/* 广度优先遍历 */// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点List<Vertex>graphBFS(GraphAdjListgraph,VertexstartVet){// 顶点遍历序列List<Vertex>res=newArrayList<>();// 哈希集合,用于记录已被访问过的顶点Set<Vertex>visited=newHashSet<>();visited.add(startVet);// 队列用于实现 BFSQueue<Vertex>que=newLinkedList<>();que.offer(startVet);// 以顶点 vet 为起点,循环直至访问完所有顶点while(!que.isEmpty()){Vertexvet=que.poll();// 队首顶点出队res.add(vet);// 记录访问顶点// 遍历该顶点的所有邻接顶点for(VertexadjVet:graph.adjList.get(vet)){if(visited.contains(adjVet))continue;// 跳过已被访问的顶点que.offer(adjVet);// 只入队未访问的顶点visited.add(adjVet);// 标记该顶点已被访问}}// 返回顶点遍历序列returnres;}