通用模板/* 回溯算法框架 */voidbacktrack(Statestate,ListChoicechoices,ListStateres){// 判断是否为解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,SetVertexvisited,ListVertexres,Vertexvet){res.add(vet);// 记录访问顶点visited.add(vet);// 标记该顶点已被访问// 遍历该顶点的所有邻接顶点for(VertexadjVet:graph.adjList.get(vet)){if(visited.contains(adjVet))continue;// 跳过已被访问的顶点// 递归访问邻接顶点dfs(graph,visited,res,adjVet);}}/* 深度优先遍历 */// 使用邻接表来表示图以便获取指定顶点的所有邻接顶点ListVertexgraphDFS(GraphAdjListgraph,VertexstartVet){// 顶点遍历序列ListVertexresnewArrayList();// 哈希集合用于记录已被访问过的顶点SetVertexvisitednewHashSet();dfs(graph,visited,res,startVet);returnres;}图的宽度优先搜索/* 广度优先遍历 */// 使用邻接表来表示图以便获取指定顶点的所有邻接顶点ListVertexgraphBFS(GraphAdjListgraph,VertexstartVet){// 顶点遍历序列ListVertexresnewArrayList();// 哈希集合用于记录已被访问过的顶点SetVertexvisitednewHashSet();visited.add(startVet);// 队列用于实现 BFSQueueVertexquenewLinkedList();que.offer(startVet);// 以顶点 vet 为起点循环直至访问完所有顶点while(!que.isEmpty()){Vertexvetque.poll();// 队首顶点出队res.add(vet);// 记录访问顶点// 遍历该顶点的所有邻接顶点for(VertexadjVet:graph.adjList.get(vet)){if(visited.contains(adjVet))continue;// 跳过已被访问的顶点que.offer(adjVet);// 只入队未访问的顶点visited.add(adjVet);// 标记该顶点已被访问}}// 返回顶点遍历序列returnres;}