From 60c64ea8e1714f904ee6d7a18b215ffc4eea49df Mon Sep 17 00:00:00 2001 From: Ramadas Kamat <54147340+Ramadas-Kamat@users.noreply.github.com> Date: Wed, 5 Oct 2022 19:31:31 +0530 Subject: [PATCH 1/2] Adding ShortestPathVisitingAllNodes file Java code for leetcode hard problem ShortestPathVisitingAllNodes --- Hard/ShortestPathVisitingAllNodes.java | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Hard/ShortestPathVisitingAllNodes.java diff --git a/Hard/ShortestPathVisitingAllNodes.java b/Hard/ShortestPathVisitingAllNodes.java new file mode 100644 index 0000000..f4886d5 --- /dev/null +++ b/Hard/ShortestPathVisitingAllNodes.java @@ -0,0 +1,42 @@ +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 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 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; + } +} From ff907f96048fbe50fc85784d54b9fc0bc23ed214 Mon Sep 17 00:00:00 2001 From: Ramadas Kamat <54147340+Ramadas-Kamat@users.noreply.github.com> Date: Wed, 5 Oct 2022 21:47:01 +0530 Subject: [PATCH 2/2] Added question link --- Hard/ShortestPathVisitingAllNodes.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Hard/ShortestPathVisitingAllNodes.java b/Hard/ShortestPathVisitingAllNodes.java index f4886d5..3e56c2f 100644 --- a/Hard/ShortestPathVisitingAllNodes.java +++ b/Hard/ShortestPathVisitingAllNodes.java @@ -1,3 +1,7 @@ +/* +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) {