Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Hard/ShortestPathVisitingAllNodes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Shortest Path Visiting All Nodes: https://leetcode.com/problems/shortest-path-visiting-all-nodes/
*/

class Solution {
public int shortestPathLength(int[][] graph) {
if (graph.length == 1) {
return 0;
}

int n = graph.length;
int endingMask = (1 << n) - 1;
boolean[][] seen = new boolean[n][endingMask];
ArrayList<int[]> queue = new ArrayList<>();

for (int i = 0; i < n; i++) {
queue.add(new int[] {i, 1 << i});
seen[i][1 << i] = true;
}

int steps = 0;
while (!queue.isEmpty()) {
ArrayList<int[]> nextQueue = new ArrayList<>();
for (int i = 0; i < queue.size(); i++) {
int[] currentPair = queue.get(i);
int node = currentPair[0];
int mask = currentPair[1];
for (int neighbor : graph[node]) {
int nextMask = mask | (1 << neighbor);
if (nextMask == endingMask) {
return 1 + steps;
}

if (!seen[neighbor][nextMask]) {
seen[neighbor][nextMask] = true;
nextQueue.add(new int[] {neighbor, nextMask});
}
}
}
steps++;
queue = nextQueue;
}

return -1;
}
}