首页>itarticle>[leetcode] problem 847 – shortest path visiting all nodes
[leetcode] problem 847 – shortest path visiting all nodes
admin11月 13, 20200
An undirected, connected graph of N nodes (labeled 0, 1, 2, …, N-1) is given as graph.
graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j are connected.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
publicintshortestPathLength(int[][] graph){ int result = 0; int n = graph.length; int target = (1 << n) - 1; boolean[][] visit = newboolean[n][1 << n]; Queue<State> queue = new LinkedList<>();
for (int i = 0; i < n; i++) queue.offer(new State(i, 1 << i));
while (!queue.isEmpty()) { int size = queue.size();
for (int i = 0; i < size; i++) { State state = queue.poll();
if (state.visitedNode == target) return result;
for (int nextNode : graph[state.currentNode]) { int nextVisitedNode = state.visitedNode | 1 << nextNode;
近期评论