question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
semi-ordered-permutation | 1 ms solution | 1-ms-solution-by-developersusername-yx1p | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | DevelopersUsername | NORMAL | 2024-11-16T11:36:31.819560+00:00 | 2024-11-16T11:36:31.819592+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n\n int n = nums.length, f = 0, l = 0;\n for (int i = 0; i < n; i++)\n if (nums[i] == 1)\n f = i;\n else if (nums[i] == n)\n l = i;\n \n int k = f < l ? 1 : 2;\n \n return f + n - l - k;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Java || Beats 100% | java-beats-100-by-swapnil-chhatre-4g7h | \nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int pos1 = 0;\n int pos2 = 0;\n \n for(int i = 0; i < nums | swapnil-chhatre | NORMAL | 2024-11-11T05:19:16.937175+00:00 | 2024-11-11T05:19:16.937216+00:00 | 3 | false | ```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int pos1 = 0;\n int pos2 = 0;\n \n for(int i = 0; i < nums.length; i++) {\n if(nums[i] == 1)\n pos1 = i;\n else if(nums[i] == nums.length)\n pos2 = i;\n }\n \n // if 1 is present at a position greater than position of n\n // then one swap will be common\n if(pos1 > pos2)\n pos2++;\n \n return pos1 - 0 + nums.length - 1 - pos2;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Easy C++ Code (Beats 100%) | easy-c-code-beats-100-by-ai1a_2310812-n2xo | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ai1a_2310812 | NORMAL | 2024-10-31T17:51:43.602972+00:00 | 2024-10-31T17:51:43.602997+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) \n {\n int n=nums.size();\n int op=0;\n auto it1=find(nums.begin(),nums.end(),1);\n int idx1=distance(nums.begin(),it1);\n for(int i=idx1;i>0;i--)\n {\n swap(nums[i],nums[i-1]);\n op++;\n }\n auto it2=find(nums.begin(),nums.end(),n);\n int idx2=distance(nums.begin(),it2);\n for(int i=idx2;i<n-1;i++)\n {\n swap(nums[i],nums[i+1]);\n op++;\n }\n return op;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Java&JS&TS Solution (JW) | javajsts-solution-jw-by-specter01wj-eou6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | specter01wj | NORMAL | 2024-10-29T20:33:24.045019+00:00 | 2024-10-29T20:33:32.499091+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\npublic int semiOrderedPermutation(int[] nums) {\n int n = nums.length;\n int index1 = -1;\n int indexN = -1;\n\n // Find the positions of 1 and n in the array\n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) index1 = i;\n if (nums[i] == n) indexN = i;\n }\n\n // Calculate moves to bring 1 to the start and n to the end\n int moves = index1 + (n - 1 - indexN);\n\n // If `1` is before `n`, no extra move needed; otherwise, one move overlaps\n if (index1 > indexN) moves -= 1;\n\n return moves;\n}\n```\n```javascript []\nvar semiOrderedPermutation = function(nums) {\n const n = nums.length;\n let index1 = -1;\n let indexN = -1;\n\n // Find the positions of 1 and n in the array\n for (let i = 0; i < n; i++) {\n if (nums[i] === 1) index1 = i;\n if (nums[i] === n) indexN = i;\n }\n\n // Calculate moves to bring 1 to the start and n to the end\n let moves = index1 + (n - 1 - indexN);\n\n // If `1` is before `n`, no extra move needed; otherwise, one move overlaps\n if (index1 > indexN) moves -= 1;\n\n return moves;\n};\n```\n```typescript []\nfunction semiOrderedPermutation(nums: number[]): number {\n const n = nums.length;\n let index1 = -1;\n let indexN = -1;\n\n // Find the positions of 1 and n in the array\n for (let i = 0; i < n; i++) {\n if (nums[i] === 1) index1 = i;\n if (nums[i] === n) indexN = i;\n }\n\n // Calculate moves to bring 1 to the start and n to the end\n let moves = index1 + (n - 1 - indexN);\n\n // If `1` is after `n`, one move overlaps, so we subtract 1\n if (index1 > indexN) moves -= 1;\n\n return moves;\n};\n``` | 0 | 0 | ['Array', 'Java', 'TypeScript', 'JavaScript'] | 0 |
semi-ordered-permutation | Easy JAVA Solution! | easy-java-solution-by-priyadarsan2509-491a | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Priyadarsan2509 | NORMAL | 2024-10-23T02:38:13.314461+00:00 | 2024-10-23T02:38:13.314490+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int n = nums.length, res = 0, i = 0;\n while(nums[0] != 1) {\n if(nums[i] == 1) {\n res++;\n nums[i] = nums[i-1];\n nums[i-1] = 1; \n i--;\n continue;\n }\n i++;\n }\n i = 0;\n while(nums[n-1] != n) {\n if(nums[i] == n) {\n res++;\n nums[i] = nums[i+1];\n nums[i+1] = n; \n }\n i++;\n }\n return res;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | The Fastest 100% Runtime JS/TS Solution | the-fastest-100-runtime-jsts-solution-by-x80d | Approach\n Describe your approach to solving the problem. \nWe find indexes of the smallest firstIndex and the largest lastIndex integers in the array.\nIf they | mirzaianov | NORMAL | 2024-10-19T11:56:09.116021+00:00 | 2024-10-19T11:56:09.116053+00:00 | 3 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nWe find indexes of the smallest `firstIndex` and the largest `lastIndex` integers in the array.\nIf they are placed at the start and at the end of the array respectively, we immediately return `0`.\nThen we check whether the index of the smallest digit is less than the index of the biggest digit. \nIf it is, we return the sum of two differences:\n- a distance between 0 and `firstIndex`,\n- a distance between `nums.length - 1` and `lastIndex`.\n\nOtherwise, we return the same with substraction of 1 as an unnesesary step for swapping.\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\nconst semiOrderedPermutation = (nums) => {\n const len = nums.length;\n const firstIndex = nums.indexOf(1);\n const lastIndex = nums.indexOf(len);\n\n if (firstIndex === 0 && lastIndex === len - 1) return 0;\n\n return firstIndex < lastIndex\n ? firstIndex + (len - 1 - lastIndex)\n : firstIndex + (len - 1 - lastIndex) - 1;\n};\n```\n\n# Code\n```typescript []\nconst semiOrderedPermutation = (nums: number[]): number => {\n const len: number = nums.length;\n const firstIndex: number = nums.indexOf(1);\n const lastIndex: number = nums.indexOf(len);\n\n if (firstIndex === 0 && lastIndex === len - 1) return 0;\n\n return firstIndex < lastIndex\n ? firstIndex + (len - 1 - lastIndex)\n : firstIndex + (len - 1 - lastIndex) - 1;\n};\n``` | 0 | 0 | ['TypeScript', 'JavaScript'] | 0 |
semi-ordered-permutation | JS | Swapping | Runtime 4 ms | Beats 100.00% | Bloated Code warning | js-swapping-runtime-4-ms-beats-10000-blo-dkh7 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | aimalkhan177 | NORMAL | 2024-10-18T15:37:21.798654+00:00 | 2024-10-18T15:37:21.798683+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar semiOrderedPermutation = function (nums) {\n if (!nums.includes(1) || !nums.includes(nums.length)) return false;\n let oneIndex = nums.indexOf(1);\n \n let minSteps = 0;\n while (nums[0] !== 1) {\n let indexOfItemBeforeOne = oneIndex - 1;\n let itemBeforeOne = nums[indexOfItemBeforeOne];\n //console.log(\'>> swapping\', itemBeforeOne, \'at\', indexOfItemBeforeOne, \'with\', nums[oneIndex], \'at\', oneIndex)\n nums[indexOfItemBeforeOne] = nums[oneIndex];\n nums[oneIndex] = itemBeforeOne;\n oneIndex = indexOfItemBeforeOne;\n minSteps++;\n }\n let lastindex = nums.indexOf(nums.length);\n while (nums[nums.length - 1] !== nums.length) {\n let indexOfItemAfterMax = lastindex + 1;\n let itemAfterMax = nums[indexOfItemAfterMax];\n nums[indexOfItemAfterMax] = nums[lastindex];\n nums[lastindex] = itemAfterMax;\n lastindex = indexOfItemAfterMax;\n minSteps++;\n }\n return minSteps;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
semi-ordered-permutation | solution for C# | solution-for-c-by-annyhuuuu-5os5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Annyhuuuu | NORMAL | 2024-10-17T13:05:44.202620+00:00 | 2024-10-17T13:05:44.202655+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```csharp []\npublic class Solution {\n public int SemiOrderedPermutation(int[] nums) {\n int times = 0;\n while(!(nums[0] == 1 && nums[nums.Length - 1] == nums.Length)){\n for (int i = 0; i < nums.Length; i++){\n if (nums[i] == 1 && i > 0) {\n for (int j = i; j >= 1; j--){\n int temp = nums[j];\n nums[j] = nums[j-1];\n nums[j-1] = temp;\n times++;\n }\n }\n else if(nums[i] == nums.Length && i < nums.Length-1){\n for (int j = i; j < nums.Length-1; j++){\n int temp = nums[j];\n nums[j] = nums[j+1];\n nums[j+1] = temp;\n times++;\n }\n i--;\n }\n }\n }\n return times;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
semi-ordered-permutation | ✅ Rust Solution | rust-solution-by-erikrios-7mdt | \nimpl Solution {\n pub fn semi_ordered_permutation(nums: Vec<i32>) -> i32 {\n let n = nums.len();\n let mut nums = nums;\n\n let mut mi | erikrios | NORMAL | 2024-10-08T03:42:22.627112+00:00 | 2024-10-08T03:42:22.627149+00:00 | 3 | false | ```\nimpl Solution {\n pub fn semi_ordered_permutation(nums: Vec<i32>) -> i32 {\n let n = nums.len();\n let mut nums = nums;\n\n let mut min_num_operations = 0;\n while !(nums[0] == 1 && nums[n - 1] == n as i32) {\n for i in 0..n {\n let num = nums[i];\n if num == 1 && i > 0 {\n let temp = nums[i - 1];\n nums[i - 1] = num;\n nums[i] = temp;\n min_num_operations += 1;\n } else if num == n as i32 && i < n - 1 {\n let temp = nums[i + 1];\n nums[i + 1] = num;\n nums[i] = temp;\n min_num_operations += 1;\n }\n }\n }\n\n min_num_operations\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
semi-ordered-permutation | Simple Approach | simple-approach-by-sssvchaitanya-dldr | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sssvchaitanya | NORMAL | 2024-10-06T10:44:44.407543+00:00 | 2024-10-06T10:44:44.407593+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int moves = 0;\n int pos1 = -1;\n int posn = -1;\n for(int i=0; i<nums.length; i++)\n {\n if(nums[i] == 1)\n {\n pos1 = i;\n }\n if(nums[i] == nums.length)\n {\n posn = i;\n }\n }\n moves = pos1 + nums.length-1 - posn;\n if(posn>pos1) return moves;\n else return moves-1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Easy To Read | Python Solution | easy-to-read-python-solution-by-werrt832-3hvk | Code\npython3 []\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n min_pos = max_pos = -1\n for i in range(len(num | werrt8321 | NORMAL | 2024-09-09T09:19:09.725812+00:00 | 2024-09-09T09:19:09.725840+00:00 | 6 | false | # Code\n```python3 []\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n min_pos = max_pos = -1\n for i in range(len(nums)):\n if nums[i] == 1:\n min_pos = i\n if nums[i] == len(nums):\n max_pos = i\n if min_pos != -1 and max_pos != -1:\n break \n \n ans = min_pos + (len(nums) - 1 - max_pos)\n return ans - 1 if min_pos > max_pos else ans\n``` | 0 | 0 | ['Python3'] | 0 |
semi-ordered-permutation | Cool 3 to 1 line solution | cool-3-to-1-line-solution-by-jafisik-yqp7 | Intuition\n Describe your first thoughts on how to solve this problem. \nCalculate the index of 1 and n (they are also the steps needed to get to the edge)\nThe | Jafisik | NORMAL | 2024-09-08T01:33:09.796840+00:00 | 2024-09-08T01:33:09.796864+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the index of 1 and n (they are also the steps needed to get to the edge)\nThen if 1 is after n in the array subtract one, because the swap would move n closer to the end. Like this 2413 -> 2143 (distance from 4 to the end was 2 and now its 1 thanks to the swap)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```csharp []\npublic class Solution {\n public int SemiOrderedPermutation(int[] nums) {\n int index1 = Array.IndexOf(nums,1);\n int indexN = Array.IndexOf(nums,nums.Length);\n return index1 + nums.Length-1 - indexN + ((index1 > indexN)?-1:0);\n\n /* Its also possible in one line, but you have to call IndexOf 2 more times (pretty expensive(but also cool)))\n return Array.IndexOf(nums,1) + (nums.Length-1) - Array.IndexOf(nums,nums.Length)\n - ((Array.IndexOf(nums,1) > Array.IndexOf(nums,nums.Length))?1:0);\n */\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
semi-ordered-permutation | JavaScript 2 pointer | javascript-2-pointer-by-donovanodom-6q93 | \nconst semiOrderedPermutation = function(nums) {\n let i = 0, j = nums.length - 1\n while(nums[i] != 1) i++\n while(nums[j] != nums.length) j--\n if(i < j) | donovanodom | NORMAL | 2024-09-06T23:34:03.768695+00:00 | 2024-09-06T23:34:03.768718+00:00 | 1 | false | ```\nconst semiOrderedPermutation = function(nums) {\n let i = 0, j = nums.length - 1\n while(nums[i] != 1) i++\n while(nums[j] != nums.length) j--\n if(i < j) return nums.length - 1 - j + i\n return nums.length - 2 - j + i\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
semi-ordered-permutation | C++ Solution | c-solution-by-user1122v-nqps | \n# Code\ncpp []\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int idxOfOne, idxOfN, n = nums.size();\n for(in | user1122v | NORMAL | 2024-09-03T09:36:49.443004+00:00 | 2024-09-03T09:36:49.443037+00:00 | 1 | false | \n# Code\n```cpp []\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int idxOfOne, idxOfN, n = nums.size();\n for(int i = 0; i < n; i++){\n if(nums[i] == 1) idxOfOne = i;\n else if(nums[i] == n) idxOfN = i;\n }\n int res = idxOfOne + (n - 1 - idxOfN);\n if(idxOfOne > idxOfN) res--;\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Python for New Leet Coder - Super Readable Solution | python-for-new-leet-coder-super-readable-rwl0 | \nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n start, end = 0, len(nums)-1\n if nums[0] == 1 and nums[-1] == l | wohcderfla | NORMAL | 2024-08-24T07:38:17.266577+00:00 | 2024-08-24T07:38:17.266613+00:00 | 4 | false | ```\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n start, end = 0, len(nums)-1\n if nums[0] == 1 and nums[-1] == len(nums):\n return 0\n \n for i in range(len(nums)):\n if nums[i] == 1:\n start = i\n if nums[i] == len(nums):\n end = i\n \n if nums[0] == 1:\n return len(nums) - end - 1\n \n if nums[-1] == len(nums):\n return start\n \n if start < end:\n return (len(nums) - end - 1) + start\n else:\n return (len(nums) - end - 1) + start - 1\n``` | 0 | 0 | ['Python'] | 0 |
semi-ordered-permutation | Python3 easy solution | python3-easy-solution-by-xnxq1-tsa0 | Since we can change neighboring elements, the result will be the summation of the indices(idx_fst_nm + n - 1 - idx_lst_nm) of the desired elements to their ref | xnxq1 | NORMAL | 2024-08-22T13:29:46.291111+00:00 | 2024-08-22T13:29:46.291136+00:00 | 2 | false | Since we can change neighboring elements, the result will be the summation of the indices(**idx_fst_nm + n - 1 - idx_lst_nm**) of the desired elements to their reference points. \nif idx_fst_nm > idx_lst_nm then we must subtract 1, since in the end they will meet and 1 less action will be needed\n\n\n**Complexity\nTime complexity: O(n)\nSpace complexity: O(1)**\n\n\n```\ndef semiOrderedPermutation(self, nums: List[int]) -> int:\n\n\tn = len(nums)\n\tidx_fst_nm, idx_lst_nm = nums.index(1), nums.index(n)\n\n\tans = idx_fst_nm + n - 1 - idx_lst_nm\n\treturn ans - 1 if idx_fst_nm > idx_lst_nm else ans\n```\n\n | 0 | 0 | ['Array', 'Math', 'Python3'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Python/Java] Dijkstra & Cached DFS - Clean & Concise | pythonjava-dijkstra-cached-dfs-clean-con-k6m2 | Idea\n- We use Dijkstra to calculate shortest distance paths from last node n to any other nodes x, the result is distanceToLastNode(x), where x in 1..n. Comple | hiepit | NORMAL | 2021-03-07T04:01:54.325354+00:00 | 2021-03-08T02:44:40.990084+00:00 | 11,037 | false | **Idea**\n- We use Dijkstra to calculate shortest distance paths from last node `n` to any other nodes `x`, the result is `distanceToLastNode(x)`, where `x in 1..n`. Complexity: `O(E * logV) = O(M logN)`, where `M` is number of edges, `N` is number of nodes.\n- In the restricted path, `[z0, z1, z2, ..., zk]`, node `zi` always stand before node `z(i+1)` because `distanceToLastNode(zi) > distanceToLastNode(zi+1)`, mean while `dfs` do calculate number of paths, a `current node` never comeback to `visited nodes`, so we don\'t need to use `visited` array to check visited nodes. Then our `dfs(src)` function only depends on one param `src`, we can use memory cache to cache precomputed results of `dfs` function, so the time complexity can be deduced to be `O(E)`.\n\n**Complexity:**\n- Time: `O(M * logN)`, where `M` is number of edges, `N` is number of nodes.\n- Space: `O(M + N)`\n\n**Python 3**\n```python\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n if n == 1: return 0\n graph = defaultdict(list)\n for u, v, w in edges:\n graph[u].append((w, v))\n graph[v].append((w, u))\n\n def dijkstra(): # Dijkstra to find shortest distance of paths from node `n` to any other nodes\n minHeap = [(0, n)] # dist, node\n dist = [float(\'inf\')] * (n + 1)\n dist[n] = 0\n while minHeap:\n d, u = heappop(minHeap)\n if d != dist[u]: continue\n for w, v in graph[u]:\n if dist[v] > dist[u] + w:\n dist[v] = dist[u] + w\n heappush(minHeap, (dist[v], v))\n return dist\n\n @lru_cache(None)\n def dfs(src):\n if src == n: return 1 # Found a path to reach to destination\n ans = 0\n for _, nei in graph[src]:\n if dist[src] > dist[nei]:\n ans = (ans + dfs(nei)) % 1000000007\n return ans\n \n dist = dijkstra()\n return dfs(1)\n```\n\n**Java**\n```java\nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n if (n == 1) return 0;\n List<int[]>[] graph = new List[n+1];\n for (int i = 1; i <= n; i++) graph[i] = new ArrayList<>();\n for (int[] e : edges) {\n graph[e[0]].add(new int[]{e[2], e[1]});\n graph[e[1]].add(new int[]{e[2], e[0]});\n }\n int[] dist = dijkstra(n, graph);\n return dfs(1, n, graph, dist, new Integer[n+1]);\n }\n // Dijkstra to find shortest distance of paths from node `n` to any other nodes\n int[] dijkstra(int n, List<int[]>[] graph) {\n int[] dist = new int[n+1];\n Arrays.fill(dist, Integer.MAX_VALUE);\n dist[n] = 0;\n PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); // dist, node\n minHeap.offer(new int[]{0, n});\n while (!minHeap.isEmpty()) {\n int[] top = minHeap.poll();\n int d = top[0], u = top[1];\n if (d != dist[u]) continue;\n for (int[] nei : graph[u]) {\n int w = nei[0], v = nei[1];\n if (dist[v] > dist[u] + w) {\n dist[v] = dist[u] + w;\n minHeap.offer(new int[]{dist[v], v});\n }\n }\n }\n return dist;\n }\n int dfs(int src, int n, List<int[]>[] graph, int[] dist, Integer[] memo) {\n if (memo[src] != null) return memo[src];\n if (src == n) return 1; // Found a path to reach to destination\n int ans = 0;\n for (int[] nei : graph[src]) {\n int w = nei[0], v = nei[1];\n if (dist[src] > dist[v])\n ans = (ans + dfs(v, n, graph, dist, memo)) % 1000000007;\n }\n return memo[src] = ans;\n }\n}\n```\n | 147 | 8 | [] | 27 |
number-of-restricted-paths-from-first-to-last-node | [Java] - Dijkstra's + DFS + Memoization + Explanation of problem description | java-dijkstras-dfs-memoization-explanati-hog9 | As a note I spent 40 minutes trying to understand what this problem was asking. In classic fashion it finally dawned on me with 5 minutes left in the contest. I | kniffina | NORMAL | 2021-03-07T04:37:56.775675+00:00 | 2021-03-08T04:38:26.494150+00:00 | 4,733 | false | As a note I spent 40 minutes trying to understand what this problem was asking. In classic fashion it finally dawned on me with 5 minutes left in the contest. I will try to explain below what the problem failed to explain (in my opinion). \n\n* Everything is pretty straight forward in the first two paragraphs. We get some edges that represent an undirected path between two different vertices. These paths are weighted. The path we are interested in is the one from `start` (node 1), to `end` (node `n`). Nothing new or overly complicated with this.\n\nThen comes this paragraph which can be very confusing as to what the question is asking you to accomplish. `The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.` \n\n* After understanding the problem this makes sense but I think there should be some clarification. *If you are vertex x, then `distanceToLastNode(x)` is the shorteset path from the end vertex `n` to the vertex you are currently visiting `x`*. \n\n* I also think adding another line to clarify that you can travel to neighboring nodes, BUT you can only do so if the distance calculated for the neighboring node is less than the cost it took to travel to the node you are moving from. In other words, you can travel to neighboring nodes ONLY if the cost calculated from `distanceToLastNode(currentNode)` is less than `distanceToLastNode(neighbor)`.\n\n**Okay getting into the problem, it is broken into 3 different steps.**\n1) Create the graph. You can use a multitude of different data structures but you want to add all the edges in an undirected manner and keep track of the weights (you will use them later).\n\n2) Using Dijkstra\'s algorithm create the shortest path distance between vertex `n` and all other nodes. Now we have all the shortest paths from each node to the end, we will call this `distanceToEnd(node)`\n\n3) Start a DFS traversal from the start node `1` and travel as many different paths that you can. **HOWEVER** the requirement is that you can only move from a node to its neighbor if `distanceToEnd(node) > distanceToEnd(nei)`.\n\t* It is possible that we can travel multiple paths that reach the same node in its path, so we save those calculations for faster lookups. \n\nI hope this helps and if you have any questions feel free to ask.\n**Please upvote if this helped you!**\n\n```\nclass Solution {\n private Map<Integer, List<int[]>> map = new HashMap<>();\n private final static int mod = 1_000_000_007;\n \n public int countRestrictedPaths(int n, int[][] edges) {\n for(int[] e : edges) {\n map.computeIfAbsent(e[0], x -> new ArrayList<>()).add(new int[] { e[1], e[2] }); //create graph with weights\n map.computeIfAbsent(e[1], x -> new ArrayList<>()).add(new int[] { e[0], e[2] });\n }\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] - b[1]); //sort based on weight (Dijkstra\'s)\n pq.offer(new int[]{ n, 0 });\n int[] dist = new int[n+1];\n Arrays.fill(dist, Integer.MAX_VALUE); \n dist[n] = 0;\n \n while(!pq.isEmpty()) {\n int[] curr = pq.poll();\n int node = curr[0];\n\t\t\tint weight = curr[1];\n \n for(int[] neighbor : map.get(node)) {\n int nei = neighbor[0];\n int w = weight + neighbor[1];\n \n if(w < dist[nei]) { //only traverse if this will create a shorter path. At the end we have all the shortest paths for each node from the last node, n.\n dist[nei] = w;\n pq.offer(new int[]{ nei, w });\n }\n }\n }\n Integer[] dp = new Integer[n+1];\n return dfs(1, n, dist, dp);\n }\n public int dfs(int node, int end, int[] dist, Integer[] dp) {\n if(node == end) return 1;\n if(dp[node] != null) return dp[node];\n long res = 0;\n for(int[] neighbor : map.get(node)) {\n int nei = neighbor[0];\n if(dist[node] > dist[nei]) { //use our calculations from Dijkstra\'s to determine if we can travel to a neighbor.\n res = (res + (dfs(nei, end, dist, dp)) % mod);\n }\n }\n res = (res % mod);\n return dp[node] = (int) res; //memoize for looking up values that have already been computed.\n }\n}\n``` | 124 | 0 | [] | 11 |
number-of-restricted-paths-from-first-to-last-node | c++ Djikstra and dfs | c-djikstra-and-dfs-by-codingmission-bp66 | Please upvote if you find this useful\n\nDefinition of Restricted Paths : Path from source node(n) to target node(1) should have strictly increasing shortest di | codingmission | NORMAL | 2021-03-07T04:00:40.718814+00:00 | 2021-03-07T04:24:05.807387+00:00 | 6,693 | false | **Please upvote if you find this useful**\n\nDefinition of Restricted Paths : Path from source node(n) to target node(1) should have strictly increasing shortest distance to source(n) for all nodes in path.\n\n- Idea is to calculate shortest distance from node n to all nodes and save it in dist array.\n- Then use dfs from source to all the nodes whose weight is greater than source node. \n- Return 1 if we have reached node 1 or return saved value for source if it\'s value is not -1(which means it\'s not visited yet)\n- Save the result for reuse later.\n- Return result. (this is the count of Restricted paths)\n\n```\ntypedef pair<int, int> pii;\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n unordered_map<int, vector<pair<int, int>>> gp;\n for (auto& edge : edges) {\n gp[edge[0]].push_back({edge[1], edge[2]});\n gp[edge[1]].push_back({edge[0], edge[2]});\n }\n \n vector<int> dist(n + 1, INT_MAX);\n priority_queue<pii, vector<pii>, greater<pii> > pq;\n pq.push({0, n});\n dist[n] = 0;\n \n\t\tint u, v, w;\n while (!pq.empty()) {\n pii p = pq.top(); pq.pop();\n u = p.second;\n for (auto& to : gp[u]) {\n v = to.first, w = to.second;\n if (dist[v] > dist[u] + w) {\n dist[v] = dist[u] + w;\n pq.push({dist[v], v});\n }\n }\n }\n vector<int> dp(n + 1, -1);\n return dfs(gp, n, dp, dist);\n }\n \n int dfs(unordered_map<int, vector<pair<int, int>>>& gp, int s, vector<int>& dp, vector<int>& dist) {\n int mod = 1e9+7;\n if (s == 1) return 1;\n if (dp[s] != -1) return dp[s];\n int sum = 0, weight, val;\n for (auto& n : gp[s]) {\n weight = dist[s];\n val = dist[n.first];\n if (val > weight) {\n sum = (sum % mod + dfs(gp, n.first, dp, dist) % mod) % mod;\n }\n }\n return dp[s] = sum % mod;\n }\n};\n```\n | 79 | 1 | ['C'] | 8 |
number-of-restricted-paths-from-first-to-last-node | C++ Dijkstra + DP | c-dijkstra-dp-by-lzl124631x-nm3u | See my latest update in repo LeetCode\n\n## Solution 1. Dijkstra + DP\n\nWe run Dijkstra algorithm starting from the nth node. \n\nLet dist[u] be the distance f | lzl124631x | NORMAL | 2021-03-07T05:45:02.654055+00:00 | 2021-03-07T05:49:18.023391+00:00 | 3,258 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Dijkstra + DP\n\nWe run Dijkstra algorithm starting from the `n`th node. \n\nLet `dist[u]` be the distance from the `u` node to `n`th node.\n\nLet `cnt[u]` be the number of restricted path from `u` node to `n`th node.\n\nEach time we visit a new node `u`, we can update its `cnt[u]` to be the sum of `cnt[v]` where `v` is a neighbor of `u` and `dist[v]` is smaller than `dist[u]`.\n\nThe answer is `cnt[0]`.\n\n```cpp\n// OJ: https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/\n// Author: github.com/lzl124631x\n// Time: O(ElogE)\n// Space: O(E)\nclass Solution {\n typedef pair<int, int> PII;\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& E) {\n long mod = 1e9 + 7;\n vector<vector<pair<long, int>>> G(n);\n for (auto &e : E) {\n int u = e[0] - 1, v = e[1] - 1, w = e[2];\n G[u].emplace_back(v, w);\n G[v].emplace_back(u, w);\n }\n priority_queue<PII, vector<PII>, greater<PII>> pq;\n vector<long> dist(n, INT_MAX), cnt(n, 0);\n dist[n - 1] = 0;\n cnt[n - 1] = 1;\n pq.emplace(0, n - 1);\n while (pq.size()) {\n auto [w, u] = pq.top();\n pq.pop();\n if (w > dist[u]) continue;\n for (auto &[v, d] : G[u]) {\n if (dist[v] > w + d) {\n dist[v] = w + d;\n pq.emplace(dist[v], v);\n }\n if (w > dist[v]) {\n cnt[u] = (cnt[u] + cnt[v]) % mod;\n }\n }\n }\n return cnt[0];\n }\n};\n``` | 50 | 0 | [] | 6 |
number-of-restricted-paths-from-first-to-last-node | C++ BFS + DFS | c-bfs-dfs-by-votrubac-wuvv | This problem was difficult for me to understand. Though, when I finally was able to unpack it, implementing it did not seem that hard.\n\n> Update: the initial | votrubac | NORMAL | 2021-03-07T16:18:10.507729+00:00 | 2021-03-12T17:32:48.315682+00:00 | 2,582 | false | This problem was difficult for me to understand. Though, when I finally was able to unpack it, implementing it did not seem that hard.\n\n> Update: the initial solution was accepted (< 500 ms), but now it gives TLE. We now need to use a priority queue for picking the next number during BFS.\n\n**BFS**\nTo figure out restricted paths, we first need to compute the distance to the last node for each node `i`.\n\nWe can do it using BFS (Dijkstra\'s) **starting from the last node**. In the code below, the distance for each node is stored in `dist`.\n\n**DFS**\nNow, we need to accumulate the number of restricted paths:\n- For the first node, the number of paths is `1`.\n- For node `i`, the number is a sum of restricted paths for all connected nodes `j`, where and `dist[i] < dist[j]`.\n\nWe can compute this using DFS, and we need to memoise the results in `dp` to avoid recomputation.\n\n**C++**\n```cpp\nint dfs(vector<vector<pair<int, int>>> &al, vector<int> &dist, vector<int> &dp, int i) {\n if (i == 1)\n return 1;\n if (dp[i] == -1) {\n dp[i] = 0;\n for (auto [j, w] : al[i])\n if (dist[i] < dist[j])\n dp[i] = (dp[i] + dfs(al, dist, dp, j)) % 1000000007;\n }\n return dp[i];\n}\nint countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int, int>>> al(n + 1);\n vector<int> dist(n + 1), dp(n + 1, -1);\n for (auto &e : edges) {\n al[e[0]].push_back({e[1], e[2]});\n al[e[1]].push_back({e[0], e[2]});\n }\n priority_queue<pair<int, int>, vector<pair<int, int>>> pq;\n pq.push({0, n});\n while (!pq.empty()) {\n auto i = pq.top().second; pq.pop();\n for (auto [j, w] : al[i]) {\n if (j != n && (dist[j] == 0 || dist[j] > dist[i] + w)) {\n dist[j] = dist[i] + w;\n pq.push({-dist[j], j});\n }\n }\n }\n return dfs(al, dist, dp, n);\n}\n``` | 23 | 1 | [] | 4 |
number-of-restricted-paths-from-first-to-last-node | [Python] One-pass Dijkstra with PriorityQueue, no extra DP | python-one-pass-dijkstra-with-priorityqu-3djj | \n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n adj = [dict() for i in range(n + 1)]\n for u, v, wgt in edges:\n | otoc | NORMAL | 2021-03-07T04:05:09.332494+00:00 | 2021-03-07T04:29:23.550925+00:00 | 1,665 | false | ```\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n adj = [dict() for i in range(n + 1)]\n for u, v, wgt in edges:\n adj[u][v] = wgt\n adj[v][u] = wgt\n # Dijkstra\'s algorithm\n dist = [float(\'inf\') for _ in range(n)] + [0]\n num_res_paths = [0 for _ in range(n)] + [1]\n Q = PriorityQueue()\n Q.put((0, n))\n visited = [False for i in range(n + 1)]\n while Q:\n min_dist, u = Q.get()\n if visited[u]:\n continue\n visited[u] = True\n if u == 1:\n break\n for v in adj[u]:\n if not visited[v]:\n alt = dist[u] + adj[u][v]\n if alt < dist[v]:\n dist[v] = alt\n Q.put((alt, v))\n if dist[v] > dist[u]:\n num_res_paths[v] = (num_res_paths[v] + num_res_paths[u]) % (10 ** 9 + 7)\n return num_res_paths[1]\n``` | 17 | 1 | [] | 5 |
number-of-restricted-paths-from-first-to-last-node | C++ | Explanation | Easy to understand | c-explanation-easy-to-understand-by-vina-x6hx | \tC++ Code with explanation \n\t\n\t\n\tWe can use dijsktra Algorithm for finding the distance from src = lastNode to each node. \n\tBecause the constraints 0< | vinayakdhimang | NORMAL | 2021-03-07T04:23:15.471673+00:00 | 2021-07-03T09:46:23.596252+00:00 | 1,272 | false | \tC++ Code with explanation \n\t\n\t\n\tWe can use dijsktra Algorithm for finding the distance from src = lastNode to each node. \n\tBecause the constraints 0<=n<=2 * 10 ^4 so that dijsktra (n^2) won\'t be work for this we \n\tuse Min-Heap (in C++ standard template library (STL) we use Priority queue).\n\t\n\t\n\tAnd Then we can apply DFS for finding all paths which have the property (dist[i]>dist[i+1]) \n\tand 0<=i<=k-1.\n\twhere k is size of sequence from node 1 to node n.\n\n\n\n\tclass Solution {\n\t\t\t\tpublic:\n\t\t\t\t\tconst int mod = 1e9+7;\n\t\t\t\t\tint dp[20005];\n\t\t\t\t\tint dfs(int start,vector<pair<int,int>>adj[],int n,int dist[])\n\t\t\t\t\t{\n\t\t\t\t\t\tif(start==n)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(dp[start]!=-1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn dp[start];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint ans = 0;\n\t\t\t\t\t\tfor(auto x:adj[start])\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tif(dist[start]>dist[x.first])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tans = (ans + dfs(x.first,adj,n,dist))%mod;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn dp[start] = ans%mod;\n\t\t\t\t\t}\n\n\t\t\t\t\tint countRestrictedPaths(int n, vector<vector<int>>& edges) {\n\n\n\t\t\t\t\t\tint dist[n+1];\n\t\t\t\t\t\tmemset(dist,INT_MAX,sizeof(dist));\n\n\t\t\t\t\t\tmemset(dp,-1,sizeof(dp));\n\t\t\t\t\t\tvector<pair<int,int>>adj[n+1];\n\t\t\t\t\t\tfor(auto x:edges)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tadj[x[0]].push_back({x[1],x[2]}); \n\t\t\t\t\t\t\tadj[x[1]].push_back({x[0],x[2]});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbool vis[n+1];\n\t\t\t\t\t\tmemset(vis,false,sizeof(vis));\n\t\t\t\t\t\tpriority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;\n\t\t\t\t\t\tdist[n] = 0;\n\t\t\t\t\t\tpq.push({0,n});\n\t\t\t\t\t\tfor(int i = 0;i<n;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdist[i] = INT_MAX;\n\t\t\t\t\t\t}\n\t\t\t\t\t\twhile(!pq.empty())\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tauto cur = pq.top();\n\t\t\t\t\t\t\tpq.pop();\n\t\t\t\t\t\t\tint u = cur.second;\n\t\t\t\t\t\t\tvis[u] = true;\n\n\n\t\t\t\t\t\t\tfor(auto v:adj[u])\n\t\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\tif(!vis[v.first] and dist[u]!=INT_MAX and dist[u]+v.second < dist[v.first])\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t dist[v.first] = dist[u] + v.second; \n\t\t\t\t\t\t\t\t\tpq.push({dist[v.first],v.first});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn dfs(1,adj,n,dist);\n\n\t\t\t\t\t}\n\t\t\t\t}; | 10 | 0 | [] | 4 |
number-of-restricted-paths-from-first-to-last-node | [C++] Detailed Explanation | Easy Approach | DFS | c-detailed-explanation-easy-approach-dfs-bd6x | Question Explanation:\nConsider ntoxSD[x] as the shortest distance of a path between node n and node x.\nFind the number of paths from node 1 that leads to node | isha_070_ | NORMAL | 2021-10-18T10:52:37.818099+00:00 | 2022-07-16T16:09:19.672358+00:00 | 959 | false | **Question Explanation:**\nConsider ```ntoxSD[x]``` as the shortest distance of a path between ```node n``` and ```node x```.\nFind the number of paths from ```node 1``` that leads to ```node n``` such that all the nodes you come across while traversing that path has ```ntoxSD[node]``` in decreasing order.\n\n\n**Solution Approach:**\nStep 1: Make adjacency list.\nStep 2: Find shortest distance from the ```node n``` to all the nodes (using Dijkstra\'s Algorithm)\nStep 3: Do DFS from ```node 1``` and considering the path that leads to the ```node n``` follows the given condition (using memoization)\n\n\n**Code:**\n```\nclass Solution {\npublic:\n int MOD=1e9+7;\n\t\n\t\n\t// Step 3.\n // to calculate the required output using dfs and memoization\n // storing the number of paths from a node (index of mem) that leads to the nth node with ntoxSD in decreasing order in vector mem\n int computeRequiredAnswer(int cnode, int n, vector<int> &mem, vector<int> &dist, int &ans, vector<vector<pair<int, int>>> &graph) {\n\t\t// if we have reached the node n\n if(cnode==n-1)\n return 1;\n \n\t\t// if we have already computed for the current node\n if(mem[cnode]!=-1)\n return mem[cnode];\n \n\t\t// to compute mem[current node]\n int cval=0;\n for(auto a : graph[cnode]) {\n if(dist[a.first]<dist[cnode]) {\n cval=(cval+computeRequiredAnswer(a.first, n, mem, dist, ans, graph))%MOD;\n }\n }\n mem[cnode]=cval;\n return cval;\n }\n \n\t\n\t// Step 2.\n // to calculate shortest distance of all the nodes from nth node\n vector<int> computeShortestPath(int n, vector<vector<pair<int, int>>> &graph) {\n vector<int> dist(n, INT_MAX);\n dist[n-1]=0;\n \n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n pq.push({0, n-1});\n \n\t\t//Dijkstra\'s Algorithm\n while(!pq.empty()) {\n int cnode=pq.top().second;\n int cdist=pq.top().first;\n pq.pop();\n for(auto a : graph[cnode]) {\n if(dist[a.first] > cdist+a.second) {\n dist[a.first]=cdist+a.second;\n pq.push({dist[a.first], a.first});\n }\n }\n }\n return dist;\n }\n \n\t\n\t// Step 1.\n // main function\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int, int>>> graph(n);\n for(auto e : edges) {\n graph[e[0]-1].push_back({e[1]-1, e[2]});\n graph[e[1]-1].push_back({e[0]-1, e[2]});\n }\n \n\t\t// to store the required shortest path\n vector<int> dist;\n dist=computeShortestPath(n, graph);\n\t\t\n\t\t// to store the number of paths that follows the given condition for each node\n vector<int> mem(n, -1);\n int ans=computeRequiredAnswer(0, n, mem, dist, ans, graph);\n\t\t\n return ans;\n }\n};\n```\n*Please upvote if you find this helpful* | 7 | 0 | ['Depth-First Search', 'Memoization', 'C'] | 2 |
number-of-restricted-paths-from-first-to-last-node | Python Djikstra and count path along the way (no need dfs or dp) | python-djikstra-and-count-path-along-the-2dw3 | Just run Djikstra and use a dictionary count to keep track of the number of restricted paths to any node. Note that if we reach node v from u, then it must be t | yanx1 | NORMAL | 2021-04-06T05:48:27.938106+00:00 | 2021-04-06T05:48:27.938149+00:00 | 781 | false | Just run Djikstra and use a dictionary `count` to keep track of the number of restricted paths to any node. Note that if we reach node `v` from `u`, then it must be the case that` d[u] <= d[v] `, and we only update `count[v]` if `d[u] < d[v]` \uFF08 think about why :-) )\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n d = {n: 0}\n for i in range(1,n):\n d[i] = math.inf\n \n nb = collections.defaultdict(list)\n\n for u,v,w in edges:\n nb[u].append((v,w))\n nb[v].append((u,w))\n \n h = [(0,n)] # min heap\n visited = set()\n count = {n:1}\n while(h):\n _, u = heapq.heappop(h)\n if u not in visited:\n visited.add(u)\n for v,w in nb[u]:\n if v not in visited:\n if d[v] > d[u]:\n count[v] = count.get(v,0) + count[u]\n if d[u] + w < d[v]:\n d[v] = d[u] + w\n heapq.heappush(h, (d[v], v))\n return count[1]%(10**9+7)\n``` | 7 | 0 | [] | 2 |
number-of-restricted-paths-from-first-to-last-node | Python [Graph DP] | python-graph-dp-by-gsan-uvpa | This question combines graph algorithms with dynamic programming. For shortest distances from each source to target use Dijkstra, which I wrote in a standalone | gsan | NORMAL | 2021-03-07T04:01:57.743151+00:00 | 2021-03-07T04:01:57.743196+00:00 | 909 | false | This question combines graph algorithms with dynamic programming. For shortest distances from each source to target use Dijkstra, which I wrote in a standalone class.\n\nOnce you get the distances, consider a dynamic programming where `dp(u)` is the number of restricted paths from vertex `u` to target. We can write a top-down DP to get the total number of paths.\n\n```python\n#Generic Dijkstra\nclass GG:\n def dijkstra(self, graph, source):\n n = len(graph)\n vis = [False]*n\n weig = [math.inf]*n\n weig[source] = 0\n pq = []\n heappush(pq, (0, source))\n while pq:\n d, u = heappop(pq)\n vis[u] = True\n for v, w in graph[u]:\n if not vis[v]:\n nd = d + w\n if nd < weig[v]:\n weig[v] = nd\n heappush(pq, (nd, v))\n return weig\n\n\nclass Solution:\n def countRestrictedPaths(self, n, edges):\n #build graph\n graph = [[] for _ in range(n)]\n for u, v, w in edges:\n graph[u-1].append((v-1, w))\n graph[v-1].append((u-1, w))\n \n #get the shortest distance from all sources to target\n #this uses Dijkstra\n gg = GG()\n path_sums = gg.dijkstra(graph, n-1)\n \n #dp(u) is all restricted paths from vertex-u to target\n @lru_cache(None)\n def dp(u):\n if u==n-1:\n return 1\n ans = 0\n for v,_ in graph[u]:\n if path_sums[v] < path_sums[u]:\n ans = ans + dp(v)\n ans = ans % (10**9 + 7)\n return ans\n \n return dp(0)\n``` | 6 | 0 | [] | 3 |
number-of-restricted-paths-from-first-to-last-node | Detailed Solution || BFS-DFS-DP | detailed-solution-bfs-dfs-dp-by-ragnar11-vmh1 | Please copy the code in your compiler for better visiblity\n\n# Code\n\n//In this question first we need to find the minimum weight(smiliar to minimum distance) | ragnar1101 | NORMAL | 2023-09-03T18:33:30.677991+00:00 | 2023-09-03T18:33:30.678019+00:00 | 650 | false | Please copy the code in your compiler for better visiblity\n\n# Code\n```\n//In this question first we need to find the minimum weight(smiliar to minimum distance) it takes to reach the end node from every node\n// after that we traverse from first node in search of a valid path and we keep a count and return it\nclass Solution {\npublic:\n const int MOD = 1e9 + 7;\n\n int dfs(int node, int end, vector<int>& dis, unordered_map<int, vector<pair<int, int>>>& adj, vector<int>& dp) {\n if (node == end) {\n return dp[node]=1; // when we reach the final destination we retrun 1 which signifies a path found\n }\n\n if(dp[node]!=-1)return dp[node];\n\n int count = 0;\n\n for (auto u : adj[node]) {\n if (dis[node] > dis[u.first]) { // we only move forward when condition is satisfied\n int path = dfs(u.first, end, dis, adj, dp);\n count = (count + path) % MOD; // Update count with modular arithmetic.\n }\n }\n\n return dp[node]=count;\n }\n\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n unordered_map<int, vector<pair<int, int>>> adj;\n\n for (int i = 0; i < edges.size(); i++) {\n int u = edges[i][0];\n int v = edges[i][1];\n int wt = edges[i][2];\n\n adj[u].push_back({v, wt});\n adj[v].push_back({u, wt}); // Assuming an undirected graph\n }\n\n vector<int> dis(n + 1, INT_MAX);\n dis[n] = 0;\n\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n pq.push({0, n}); // Push the starting node with distance 0\n\n while (!pq.empty()) {\n int dist = pq.top().first;\n int node = pq.top().second;\n pq.pop();\n\n for (auto u : adj[node]) {\n int adjNode = u.first;\n int adjDist = u.second;\n\n if (dis[adjNode] > dist + adjDist) {\n dis[adjNode] = dist + adjDist;\n pq.push({dis[adjNode], adjNode});\n }\n }\n }\n // calling dfs from node 1 to last node \n //this will return no of restricated path\n vector<int> dp(n + 1, -1); // dp array\n int i = 1; //starting from node 1\n return dfs(i, n, dis, adj, dp);\n }\n};\n\n``` | 5 | 0 | ['Dynamic Programming', 'Graph', 'Heap (Priority Queue)', 'Shortest Path', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Python3] Dijkstra + Cache DFS ~ DP Top-down Memorization - Simple | python3-dijkstra-cache-dfs-dp-top-down-m-xvh6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dolong2110 | NORMAL | 2023-08-06T16:45:56.887147+00:00 | 2023-08-06T16:45:56.887164+00:00 | 379 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(V)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V + E)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n if n == 1: return 0\n g = collections.defaultdict(list)\n sum_w, mod = 0, 10 ** 9 + 7\n for u, v, w in edges:\n g[u].append((w, v))\n g[v].append((w, u))\n sum_w += w\n \n def dijkstra() -> List[int]:\n pq = [(0, n)]\n distance = [sum_w + 1 for _ in range(n + 1)]\n distance[n] = 0\n while pq:\n w, u = heapq.heappop(pq)\n for v_w, v in g[u]:\n if w + v_w < distance[v]:\n distance[v] = w + v_w\n heapq.heappush(pq, (w + v_w, v))\n return distance\n \n @cache\n def dfs(u: int) -> int:\n if u == n: return 1\n cnt = 0\n for _, v in g[u]:\n if distance[u] > distance[v]: cnt = (cnt + dfs(v)) % mod\n \n return cnt\n \n distance = dijkstra()\n return dfs(1)\n\n``` | 5 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Shortest Path', 'Python3'] | 0 |
number-of-restricted-paths-from-first-to-last-node | c++ | easy | fast | c-easy-fast-by-venomhighs7-hcr5 | \n\n# Code\n\n\nclass Solution {\n typedef pair<int, int> PII;\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& E) {\n long mod = 1e | venomhighs7 | NORMAL | 2022-11-15T04:00:42.616009+00:00 | 2022-11-15T04:00:42.616050+00:00 | 1,017 | false | \n\n# Code\n```\n\nclass Solution {\n typedef pair<int, int> PII;\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& E) {\n long mod = 1e9 + 7;\n vector<vector<pair<long, int>>> G(n);\n for (auto &e : E) {\n int u = e[0] - 1, v = e[1] - 1, w = e[2];\n G[u].emplace_back(v, w);\n G[v].emplace_back(u, w);\n }\n priority_queue<PII, vector<PII>, greater<PII>> pq;\n vector<long> dist(n, INT_MAX), cnt(n, 0);\n dist[n - 1] = 0;\n cnt[n - 1] = 1;\n pq.emplace(0, n - 1);\n while (pq.size()) {\n auto [w, u] = pq.top();\n pq.pop();\n if (w > dist[u]) continue;\n for (auto &[v, d] : G[u]) {\n if (dist[v] > w + d) {\n dist[v] = w + d;\n pq.emplace(dist[v], v);\n }\n if (w > dist[v]) {\n cnt[u] = (cnt[u] + cnt[v]) % mod;\n }\n }\n }\n return cnt[0];\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [ C++ ], Beats 100% on space and time | c-beats-100-on-space-and-time-by-harshjo-9uto | \n\t#define pi pair<int, int>\n const int mod = 1e9+7;\n vector<int> dis, vis, dp;\n vector<vector<pi>> g;\n int n;\n\t\n // FIND SHORTEST PATH F | harshjoeyit | NORMAL | 2021-03-15T04:52:55.736843+00:00 | 2021-03-15T04:52:55.736886+00:00 | 735 | false | ```\n\t#define pi pair<int, int>\n const int mod = 1e9+7;\n vector<int> dis, vis, dp;\n vector<vector<pi>> g;\n int n;\n\t\n // FIND SHORTEST PATH FROM \'n\' to ALL OTHER NODES\n void dijkstra(int u) {\n priority_queue<pi, vector<pi>, greater<pi>> pq;\n dis[u] = 0;\n pq.push({0, u});\n\n while(!pq.empty()) {\n int u = pq.top().second;\n pq.pop();\n \n if(vis[u]) {\n continue;\n }\n vis[u] = 1;\n for(auto p: g[u]) {\n int v = p.first, w = p.second;\n if(dis[u] + w < dis[v]) {\n dis[v] = dis[u] + w;\n pq.push({dis[v], v});\n }\n }\n }\n }\n \n\t// FIND PATHS WITH DECREASING DISTANCES TO \'n\'\n int dfs(int u) {\n if(u == n) {\n return 1;\n }\n if(dp[u] != -1) {\n return dp[u];\n }\n \n dp[u] = 0;\n for(auto p: g[u]) {\n int v = p.first;\n if(dis[v] < dis[u]) {\n dp[u] = (dp[u] + dfs(v)) % mod;\n }\n }\n return dp[u];\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n this->n = n;\n dis.assign(n+1, INT_MAX);\n vis.assign(n+1, 0);\n g.assign(n+1, vector<pi>());\n\n for(auto e: edges) {\n int u = e[0], v = e[1], w = e[2];\n g[u].push_back({v, w});\n g[v].push_back({u, w});\n }\n \n dijkstra(n);\n dp.assign(n+1, -1);\n return dfs(1);\n }\n``` | 5 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Shortest Path'] | 1 |
number-of-restricted-paths-from-first-to-last-node | [Python3] Dijkstra + dp | python3-dijkstra-dp-by-ye15-ewi5 | \n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v | ye15 | NORMAL | 2021-03-07T04:02:44.298236+00:00 | 2021-03-08T04:30:40.734378+00:00 | 895 | false | \n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n queue = [n]\n dist = {n: 0}\n while queue: \n newq = []\n for u in queue: \n for v, w in graph[u]:\n if v not in dist or dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n newq.append(v)\n queue = newq\n \n @cache\n def fn(u): \n """Return number of restricted paths from u to n."""\n if u == n: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(1) % 1_000_000_007\n```\n\nEdited on 3/7/2021\nAdding the implemetation via Dijkstra\'s algo\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u-1, []).append((v-1, w))\n graph.setdefault(v-1, []).append((u-1, w))\n \n # dijkstra\'s algo\n pq = [(0, n-1)]\n dist = [inf]*(n-1) + [0]\n while pq: \n d, u = heappop(pq)\n for v, w in graph[u]: \n if dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n heappush(pq, (dist[v], v))\n \n @cache\n def fn(u): \n """Return number of restricted paths from u to n."""\n if u == n-1: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(0) % 1_000_000_007\n``` | 5 | 0 | ['Python3'] | 1 |
number-of-restricted-paths-from-first-to-last-node | Easy One Pass Dijkstra Solution || No DFS + DP required | easy-one-pass-dijkstra-solution-no-dfs-d-ciuk | Approach\nApproach:\nThe approach to solve this problem is based on a combination of Dijkstra\'s algorithm for shortest paths and dynamic programming.\n\nShorte | sakshamsharma809 | NORMAL | 2024-06-19T11:42:56.139146+00:00 | 2024-06-19T11:42:56.139176+00:00 | 308 | false | # Approach\nApproach:\nThe approach to solve this problem is based on a combination of Dijkstra\'s algorithm for shortest paths and dynamic programming.\n\nShortest Path Calculation (Dijkstra\'s Algorithm):\n\nWe start by calculating the shortest distance from every node to node n using Dijkstra\'s algorithm.\nWe use a priority queue (min-heap) to efficiently get the next node with the smallest distance.\n\nCounting Restricted Paths:\n\nUsing the distances calculated, we determine the number of restricted paths from node 1 to node n.\nWe use a priority queue to process nodes in the order of their distance from node n, ensuring that when we process a node, all nodes with shorter distances have already been processed.\nFor each node x, for each neighbor y, if the distance to n from y is greater than from x (dist[y] > dist[x]), it means we can move from x to y in a restricted path. We then update the number of restricted paths to y by adding the number of restricted paths to x.\n\n# Complexity\n- Time complexity:\nGraph Construction: O(E)\nDijkstra\'s Algorithm: O(V + E)logV\n\n\n- Space complexity:\nGraph Representation: O(E + V)\nDistance and Path Arrays: O(V)\nPriority Queue: O(V)\n\n# Code\n```\nclass Pair {\n int node, weight;\n \n Pair(int node, int weight) {\n this.node = node;\n this.weight = weight;\n }\n}\n\nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n List<List<Pair>> adj = new ArrayList<>();\n for (int i = 0; i <= n; i++) {\n adj.add(new ArrayList<>());\n }\n\n for (int[] edge : edges) {\n int u = edge[0], v = edge[1], w = edge[2];\n adj.get(u).add(new Pair(v, w));\n adj.get(v).add(new Pair(u, w));\n }\n\n int[] dist = new int[n + 1];\n int[] ans = new int[n + 1];\n Arrays.fill(dist, Integer.MAX_VALUE);\n dist[n] = 0;\n ans[n] = 1;\n PriorityQueue<Pair> heap = new PriorityQueue<>((a, b) -> a.weight - b.weight);\n heap.offer(new Pair(n, 0));\n int mod = (int) 1e9 + 7;\n\n while (!heap.isEmpty()) {\n Pair top = heap.poll();\n int d = top.weight, x = top.node;\n if (d > dist[x]) continue;\n if (x == 1) break;\n for (Pair neighbor : adj.get(x)) {\n int y = neighbor.node, w = neighbor.weight;\n if (dist[y] > dist[x] + w) {\n dist[y] = dist[x] + w;\n heap.offer(new Pair(y, dist[y]));\n }\n if (dist[y] > dist[x]) {\n ans[y] = (ans[y] + ans[x]) % mod;\n }\n }\n }\n return ans[1];\n }\n}\n``` | 4 | 0 | ['Dynamic Programming', 'Graph', 'Topological Sort', 'Heap (Priority Queue)', 'Shortest Path', 'Java'] | 1 |
number-of-restricted-paths-from-first-to-last-node | Python 3 | Dijkstra, DFS, DAG pruning | Explanation | python-3-dijkstra-dfs-dag-pruning-explan-zmrr | Implementation\n- The solution is basically an implementation based on hint, please seee below comments for detail\n### Explanation\n\nclass Solution:\n def | idontknoooo | NORMAL | 2021-08-29T06:43:08.548232+00:00 | 2021-08-29T06:43:08.548265+00:00 | 767 | false | ### Implementation\n- The solution is basically an implementation based on `hint`, please seee below comments for detail\n### Explanation\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = collections.defaultdict(list) # build graph\n for a, b, w in edges:\n graph[a].append((w, b))\n graph[b].append((w, a))\n heap = graph[n]\n heapq.heapify(heap)\n d = {n: 0}\n while heap: # Dijkstra from node `n` to other nodes, record shortest distance to each node\n cur_w, cur = heapq.heappop(heap)\n if cur in d: continue\n d[cur] = cur_w\n for w, nei in graph[cur]:\n heapq.heappush(heap, (w+cur_w, nei))\n graph = collections.defaultdict(list)\n for a, b, w in edges: # pruning based on `restricted` condition, make undirected graph to directed-acyclic graph\n if d[a] > d[b]:\n graph[a].append(b)\n elif d[a] < d[b]:\n graph[b].append(a)\n ans, mod = 0, int(1e9+7)\n @cache\n def dfs(node): # use DFS to find total number of paths\n if node == n:\n return 1\n cur = 0 \n for nei in graph[node]:\n cur = (cur + dfs(nei)) % mod\n return cur \n return dfs(1)\n``` | 4 | 1 | ['Depth-First Search', 'Python', 'Python3'] | 2 |
number-of-restricted-paths-from-first-to-last-node | [Java] Dijkshtra + memoization | java-dijkshtra-memoization-by-valarmorgh-4w3w | \nclass Solution {\n int dp[];\n //We use memoization\n public int countRestrictedPaths(int n, int[][] edges) {\n int[] dist = new int[n+1];\n | valarmorghulis89 | NORMAL | 2021-03-07T04:02:56.860524+00:00 | 2021-03-07T04:02:56.860566+00:00 | 937 | false | ```\nclass Solution {\n int dp[];\n //We use memoization\n public int countRestrictedPaths(int n, int[][] edges) {\n int[] dist = new int[n+1];\n dp = new int[n+1];\n Arrays.fill(dp,-1);\n Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();\n //Create the graph from input edges\n for(int[] e : edges){\n graph.putIfAbsent(e[0], new HashMap<>());\n graph.putIfAbsent(e[1], new HashMap<>());\n graph.get(e[0]).put(e[1],e[2]);\n graph.get(e[1]).put(e[0],e[2]);\n }\n //Single source shortest distance - something like Dijkstra\'s\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));\n int[] base = new int[2];\n base[0]=n;\n pq.offer(base);\n while(!pq.isEmpty()){\n int[] currNode = pq.poll();\n \n for(Map.Entry<Integer, Integer> neighbour: graph.get(currNode[0]).entrySet()){\n int node = neighbour.getKey();\n int d = neighbour.getValue()+currNode[1];\n if(node==n) continue;\n //Select only those neighbours, whose new distance is less than existing distance\n //New distance = distance of currNode from n + weight of edge between currNode and neighbour\n \n if( dist[node]==0 || d < dist[node]){\n int[] newNode = new int[2];\n newNode[0]=node;\n newNode[1]=d;\n pq.offer(newNode);\n dist[node]= d;\n }\n }\n }\n\n return find(1,graph,n,dist);\n }\n //This method traverses all the paths from source node to n though it\'s neigbours\n private int find(int node, Map<Integer, Map<Integer, Integer>> graph, int n, int[] dist ){\n if(node==n){\n return 1;\n }\n \n //Memoization avoid computaion of common subproblems. \n if(dp[node]!=-1) return dp[node];\n\n int ans = 0;\n for(Map.Entry<Integer, Integer> neighbour: graph.get(node).entrySet()){\n int currNode = neighbour.getKey();\n int d = dist[currNode];\n if( dist[node] > d){\n ans = (ans + find(currNode, graph, n, dist)) % 1000000007;\n }\n }\n \n return dp[node] = ans;\n }\n}\n``` | 4 | 1 | ['Java'] | 2 |
number-of-restricted-paths-from-first-to-last-node | [C++] : Using dikstra + Toposort + DP | c-using-dikstra-toposort-dp-by-zanhd-lkmu | \n#define ll long long int\nconst ll M = 1e9 + 7;\n#define MOD_ADD(a,b,m) ((a % m) + (b % m)) % m\nclass Solution {\npublic:\n \n static bool compare(pair | zanhd | NORMAL | 2022-04-15T12:54:30.286889+00:00 | 2022-04-15T12:54:56.824288+00:00 | 414 | false | ```\n#define ll long long int\nconst ll M = 1e9 + 7;\n#define MOD_ADD(a,b,m) ((a % m) + (b % m)) % m\nclass Solution {\npublic:\n \n static bool compare(pair<ll,ll> a, pair<ll,ll> b)\n {\n return a.second > b.second; // for min heap\n }\n \n vector<ll> dikstra(ll src, vector<vector<pair<ll,ll>>> &adj, ll n)\n {\n vector<ll> dis(n, INT_MAX);\n vector<ll> vis(n, 0);\n priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, function<bool(pair<ll,ll>, pair<ll,ll>)>> Q(compare); \n \n Q.push({src, 0});\n while(!Q.empty())\n {\n pair<ll,ll> now = Q.top(); Q.pop();\n \n int u = now.first;\n \n if(vis[u]) continue;\n vis[u] = 1;\n dis[u] = now.second;\n \n for(auto x : adj[u])\n {\n int v = x.first;\n int w = x.second;\n \n if(dis[v] > dis[u] + w)\n {\n dis[v] = dis[u] + w;\n Q.push({v, dis[v]});\n }\n }\n }\n \n return dis;\n }\n \n vector<int> toposort(vector<vector<int>> &adj, int n)\n {\n vector<int> ans;\n int indegree[n + 1];\n memset(&indegree, 0x00, sizeof(indegree));\n \n for(int u = 1; u < n; u++)\n {\n for(auto v : adj[u])\n indegree[v]++;\n }\n \n queue<int> q;\n for(int i = 1; i < n; i++) if(!indegree[i]) q.push(i);\n \n while(!q.empty())\n {\n int u = q.front(); q.pop();\n ans.push_back(u);\n \n for(auto v : adj[u])\n {\n indegree[v]--;\n if(!indegree[v]) q.push(v);\n }\n }\n \n return ans;\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) \n {\n vector<vector<pair<ll,ll>>> adj(n + 1); // u - > (v, w)\n \n for(auto e : edges)\n {\n ll u = e[0];\n ll v = e[1];\n ll w = e[2];\n adj[u].push_back({v,w});\n adj[v].push_back({u, w});\n }\n \n //dis[i] = distance from i to n;\n vector<ll> dis = dikstra(n, adj, n + 1);\n \n vector<vector<int>> DAG(n + 1);\n for(auto e : edges)\n {\n int u = e[0];\n int v = e[1];\n \n if(dis[u] > dis[v]) DAG[u].push_back(v);\n if(dis[v] > dis[u]) DAG[v].push_back(u);\n }\n \n vector<int> topo = toposort(DAG, n + 1);\n \n int dp[n + 1]; memset(&dp, 0x00, sizeof(dp));\n dp[n] = 1;\n \n for(int i = topo.size() - 1; i >= 0; i--)\n {\n int u = topo[i];\n for(auto v : DAG[u])\n dp[u] = MOD_ADD(dp[u], dp[v], M);\n }\n \n \n return dp[1];\n \n return 0;\n }\n};\n``` | 3 | 0 | ['Dynamic Programming', 'Topological Sort'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Straightforward Python Dijkstra + DP - Beats 98% Runtime and Memory! | straightforward-python-dijkstra-dp-beats-kdg4 | \nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = defaultdict(dict)\n for u, v, w in edges:\ | tullya | NORMAL | 2021-05-09T02:13:40.812940+00:00 | 2021-07-30T02:16:29.300267+00:00 | 473 | false | ```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = defaultdict(dict)\n for u, v, w in edges:\n graph[u][v] = w\n graph[v][u] = w\n \n paths = [0] * (n+1)\n paths[n] = 1\n dists = [-1] * (n+1)\n pq = [(0, n)]\n \n while pq:\n dist, node = heappop(pq)\n if dists[node] != -1:\n continue\n dists[node] = dist\n for v, w in graph[node].items():\n if dists[v] == -1:\n heappush(pq, (dist + w, v))\n elif dists[v] < dists[node]:\n paths[node] += paths[v]\n paths[node] %= 10**9 + 7\n if node == 1:\n return paths[node]\n \n return 0\n``` | 3 | 0 | ['Dynamic Programming', 'Python'] | 1 |
number-of-restricted-paths-from-first-to-last-node | C# Dijkstra’s with SortedSet + DFS with Memo | O(E*Log(N^2)) time | c-dijkstras-with-sortedset-dfs-with-memo-nu0e | SortedSet works as a priority queue here. SortedSet.Add method takes Log(N^2) time in our case which leads to O(ELog(N^2)) time complexity overall where E is th | xenfruit | NORMAL | 2021-03-08T04:05:18.807507+00:00 | 2021-04-11T04:27:50.951981+00:00 | 193 | false | SortedSet works as a priority queue here. SortedSet.Add method takes Log(N^2) time in our case which leads to O(ELog(N^2)) time complexity overall where E is the number of edges and N is the number of nodes\n\n```\npublic class Solution\n{\n public int CountRestrictedPaths(int n, int[][] edges)\n {\n var graph = new Dictionary<int, List<Tuple<int, int>>>();\n for (int i = 0; i < edges.Length; i++)\n {\n AddNodeToGraph(edges[i][0], edges[i][1], edges[i][2], graph);\n AddNodeToGraph(edges[i][1], edges[i][0], edges[i][2], graph);\n }\n \n var distanceToLastNode = new Dictionary<int, int>();\n var priorityQueue = new SortedSet<Tuple<int, int>>();\n priorityQueue.Add(Tuple.Create(0, n));\n \n while (priorityQueue.Count > 0 && distanceToLastNode.Count < n)\n {\n var min = priorityQueue.Min;\n var minDist = min.Item1;\n var minNode = min.Item2;\n priorityQueue.Remove(min);\n \n if (distanceToLastNode.ContainsKey(minNode))\n continue;\n \n distanceToLastNode.Add(minNode, minDist);\n \n var nodeDists = graph[minNode];\n foreach (var nodeDist in nodeDists)\n {\n var node = nodeDist.Item1;\n var dist = nodeDist.Item2;\n if (!distanceToLastNode.ContainsKey(node))\n priorityQueue.Add(Tuple.Create(minDist + dist, node));\n }\n }\n \n return DFS(1, n, new int?[n + 1], graph, distanceToLastNode);\n }\n \n private void AddNodeToGraph(int nodeFrom, int nodeTo, int dist, Dictionary<int, List<Tuple<int, int>>> graph)\n {\n if (!graph.ContainsKey(nodeFrom))\n graph[nodeFrom] = new List<Tuple<int, int>>();\n \n graph[nodeFrom].Add(Tuple.Create(nodeTo, dist));\n }\n \n private int DFS(int currNode, int target, int?[] dp, Dictionary<int, List<Tuple<int, int>>> graph, Dictionary<int, int> distanceToLastNode)\n {\n if (dp[currNode].HasValue)\n return dp[currNode].Value;\n \n if (currNode == target)\n return 1;\n \n var result = 0;\n var nodeDists = graph[currNode];\n foreach (var nodeDist in nodeDists)\n {\n var nextNode = nodeDist.Item1;\n if (distanceToLastNode[currNode] > distanceToLastNode[nextNode])\n result = (result + DFS(nextNode, target, dp, graph, distanceToLastNode)) % (int)(1e9 + 7);\n }\n dp[currNode] = result;\n return result;\n }\n}\n``` | 3 | 1 | ['Depth-First Search'] | 1 |
number-of-restricted-paths-from-first-to-last-node | Clean Python 3, Dijkstra and top-down dp | clean-python-3-dijkstra-and-top-down-dp-ujldz | Use Dijkstra algorithm to find the shortest path from n.\nAnd use top-down dp to find all valid paths.\n\nTime: O(E + (V + E)logV + 2 * E) = O((V + E)logV)\nSpa | lenchen1112 | NORMAL | 2021-03-07T04:01:42.414336+00:00 | 2021-03-07T09:35:46.154705+00:00 | 340 | false | Use Dijkstra algorithm to find the shortest path from `n`.\nAnd use top-down dp to find all valid paths.\n\nTime: `O(E + (V + E)logV + 2 * E) = O((V + E)logV)`\nSpace: `O(E + V)`\n\n```\nimport collections\nimport functools\nimport heapq\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n @functools.cache\n def dfs(node: int) -> int:\n if node == 1: return 1\n result = 0\n for nei in graph[node]:\n if dist[nei] > dist[node]:\n result = (result + dfs(nei)) % mod\n return result\n\n graph = collections.defaultdict(dict)\n for u, v, w in edges:\n graph[u][v] = w\n graph[v][u] = w\n dist, heap, mod = {n: 0}, [(0, n)], 10**9 + 7\n while heap:\n shortest, node = heapq.heappop(heap)\n if shortest != dist[node]: continue\n for nei, w in graph[node].items():\n if dist[node] + w < dist.get(nei, float(\'inf\')):\n dist[nei] = dist[node] + w\n heapq.heappush(heap, (dist[nei], nei))\n return dfs(n)\n``` | 3 | 0 | [] | 1 |
number-of-restricted-paths-from-first-to-last-node | C++✅✅| Simplest approach (Dijkstra + DP)🚀🚀 | c-simplest-approach-dijkstra-dp-by-aayu_-yeyp | \n\n# Code\n\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<pair<int, int>> adj[n + 1];\n | aayu_t | NORMAL | 2024-06-29T04:54:54.446617+00:00 | 2024-06-29T04:54:54.446641+00:00 | 614 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<pair<int, int>> adj[n + 1];\n for(auto it : edges){\n adj[it[0]].push_back({it[1], it[2]});\n adj[it[1]].push_back({it[0], it[2]});\n }\n vector<int> dis(n + 1, INT_MAX);\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n pq.push({0, n});\n dis[n] = 0;\n while(!pq.empty()){\n auto [wt, node] = pq.top();\n pq.pop();\n for(auto [v, edgeWeight] : adj[node]) {\n if(dis[node] + edgeWeight < dis[v]) {\n dis[v] = dis[node] + edgeWeight;\n pq.push({dis[v], v});\n }\n }\n }\n vector<int> dp(n + 1, -1);\n function<int(int)> dfs = [&](int node) -> int {\n if(node == 1) return 1;\n if(dp[node] != -1) return dp[node];\n int ways = 0;\n for(auto [v, wt] : adj[node]){\n if(dis[node] < dis[v]){\n ways = (ways + dfs(v)) % 1000000007;\n }\n }\n return dp[node] = ways;\n };\n return dfs(n);\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Graph', 'Heap (Priority Queue)', 'Shortest Path', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | beats 99% c++ explaination | beats-99-c-explaination-by-mnikhil1011-u1ep | Approach\n Describe your approach to solving the problem. \nthere are multiple seperate steps to reach to the final answer\n\n1)form the adj list\n\n2)find the | mnikhil1011 | NORMAL | 2023-07-15T14:19:28.636111+00:00 | 2023-07-15T14:19:28.636136+00:00 | 376 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nthere are multiple seperate steps to reach to the final answer\n\n1)form the adj list\n\n2)find the dist of every node from last node. to do this we can use [Dijkstra\u2019s Algorithm](https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/) here we have implemented using a heap, we can also use sets.\nwe save all the distances in a vector called dist\n\n3)we now perform DFS from the first node \nin the dfs-> we go to all adj nodes and if dist from adj node is lesser then we call dfs function from that node too and when we reach node N then we return 1\nbut since this will take a lot of time we can make a dp to remember number of ways to reach end from each node this will make the code faster \n\n\n# Code\n```\nclass Solution {\n vector<int>dist;\n int node;\n int MOD=1e9+7;\n vector<int>dp;\n int dfs(int i,vector<pair<int,int>>adj[])\n {\n if(i==node)\n return 1;\n if(dp[i]!=-1)\n return dp[i];\n int ans=0;\n for(const auto & [a,b]:adj[i])\n if(dist[i]>dist[a])\n {\n ans+=dfs(a,adj);\n ans%=MOD;\n }\n\n return dp[i]=ans;\n }\n\npublic:\n // this makes the code run faster but is not needed for the code to function\n Solution()\n {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n }\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n node=n;\n vector<pair<int,int>>adj[n+1];\n dp.resize(n+1,-1);\n for(const auto & i:edges)\n {\n adj[i[0]].push_back({i[1],i[2]});\n adj[i[1]].push_back({i[0],i[2]});\n }\n\n dist.resize(n+1,INT_MAX);\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;\n q.push({0,n});\n\n while(!q.empty())\n {\n const auto [a,b]=q.top();\n q.pop();\n if(dist[b]!=INT_MAX)\n continue;\n dist[b]=a;\n for(const auto & [i,j]:adj[b])\n if(dist[i]==INT_MAX)\n q.push({a+j,i});\n \n }\n \n return dfs(1,adj);\n \n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Graph', 'Heap (Priority Queue)', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Simple Solution | simple-solution-by-java_programmer_ketan-lxaa | \nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n List<List<int[]>> undirectedEdges = new ArrayList<>();\n long[] c | Java_Programmer_Ketan | NORMAL | 2022-03-10T06:40:03.194367+00:00 | 2022-03-10T06:40:03.194411+00:00 | 244 | false | ```\nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n List<List<int[]>> undirectedEdges = new ArrayList<>();\n long[] cache = new long[n+1];\n Arrays.fill(cache,-1);\n cache[n]=1;\n for(int i=0;i<=n;i++) \n undirectedEdges.add(new ArrayList<>());\n for(int[] edge: edges) {\n undirectedEdges.get(edge[0]).add(new int[]{edge[0],edge[1],edge[2]});\n undirectedEdges.get(edge[1]).add(new int[]{edge[1],edge[0],edge[2]});\n }\n Queue<int[]> queue = new PriorityQueue<>((e1,e2)->e1[1]-e2[1]);\n int[] shortestDistance = new int[n+1];\n Arrays.fill(shortestDistance,Integer.MAX_VALUE);\n shortestDistance[n]=0;\n queue.offer(new int[]{n,shortestDistance[n]}); \n while(!queue.isEmpty()){ //dijkstra\'s algorithm\n int curVertex = queue.poll()[0];\n for(int[] edge: undirectedEdges.get(curVertex)){\n int destination = edge[1];\n int weight = edge[2];\n if(shortestDistance[curVertex]+weight<shortestDistance[destination]){\n shortestDistance[destination]=shortestDistance[curVertex]+weight;\n queue.offer(new int[]{destination,shortestDistance[destination]});\n }\n }\n\n }\n return (int)dfs(undirectedEdges,shortestDistance,1,n,cache);\n }\n public long dfs(List<List<int[]>> undirectedEdges, int[] shortestDistance, int curVertex,int n,long[] cache){\n long answer = 0;\n if(curVertex==n) return 1;\n if(cache[curVertex]!=-1) return cache[curVertex];\n for(int[] edge: undirectedEdges.get(curVertex)){\n if(shortestDistance[curVertex]>shortestDistance[edge[1]]) \n answer+=dfs(undirectedEdges,shortestDistance,edge[1],n,cache);\n }\n return cache[curVertex]=answer%1000_000_007;\n }\n}\n``` | 2 | 0 | ['Dynamic Programming'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Python] Clean + Short | Dijkstra's Algorithm + DFS + Memoization | 40 Line Solution | python-clean-short-dijkstras-algorithm-d-hupd | ```\nfrom queue import PriorityQueue\n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n g = defaultdict(dic | viktorb1 | NORMAL | 2022-02-15T23:59:59.935022+00:00 | 2022-02-16T00:07:13.058363+00:00 | 398 | false | ```\nfrom queue import PriorityQueue\n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n g = defaultdict(dict)\n \n for u, v, w in edges: # create adjacency list\n g[u][v] = w\n g[v][u] = w\n \n def dijkstras(start): # calculate shortests paths\n d = {v: float(\'inf\') for v in range(1, n+1)}\n d[start] = 0\n q = PriorityQueue()\n q.put((0, start))\n \n while not q.empty():\n u = q.get()[1]\n \n for v in g[u]:\n if d[u] + g[u][v] < d[v]:\n d[v] = d[u] + g[u][v]\n q.put((d[v], v))\n \n return d\n \n d = dijkstras(n)\n seen = set()\n \n @cache\n def dfs(node):\n if node == n:\n return 1\n \n seen.add(node)\n count = 0\n for neighbor in g[node].keys():\n if d[neighbor] < d[node] and neighbor not in seen:\n count += dfs(neighbor)\n seen.discard(node)\n return count\n \n return dfs(1) % (10**9 + 7) | 2 | 0 | ['Depth-First Search', 'Python'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra + DFS | C++ | dijkstra-dfs-c-by-prakhar3099-96u4 | \nconst int mod = 1e9+7;\n\tint dp[20005];\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n memset(dp,-1,sizeof(dp));\n | prakhar3099 | NORMAL | 2021-11-10T04:23:28.992243+00:00 | 2021-11-10T04:23:28.992308+00:00 | 324 | false | ```\nconst int mod = 1e9+7;\n\tint dp[20005];\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n memset(dp,-1,sizeof(dp));\n vector<vector<pair<int,int>>> adj(n+1);\n \n //building the adjacency matrix\n for(int i = 0; i<edges.size(); i++){\n adj[edges[i][0]].push_back({edges[i][1],edges[i][2]});\n adj[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n \n //dijkstra for nth node\n vector<int> distTo(n+1,INT_MAX);\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;\n \n pq.push({0,n});\n distTo[n] = 0;\n \n while(!pq.empty()){\n int node = pq.top().second;\n int distance = pq.top().first;\n pq.pop();\n \n for(auto x : adj[node]){\n int adjNode = x.first;\n int nextDist = x.second;\n if(distance+nextDist < distTo[adjNode]){\n distTo[adjNode] = distance+nextDist;\n pq.push({distTo[adjNode],adjNode});\n }\n }\n }\n \n vector<int> dp(n + 1, -1);\n return dfs(adj,1,n,distTo);\n }\n \n int dfs(vector<vector<pair<int,int>>>& adj, int s, int n, vector<int> &distTo){\n \n if(s == n) return 1;\n if(dp[s] != -1) return dp[s];\n \n int ans = 0;\n \n for(auto x : adj[s]){\n if(distTo[s]>distTo[x.first]){\n ans = (ans+dfs(adj,x.first,n,distTo))%mod;\n }\n }\n return dp[s] = ans%mod; \n \n }\n``` | 2 | 0 | ['Depth-First Search', 'C'] | 1 |
number-of-restricted-paths-from-first-to-last-node | java | java-by-jjyz-vi83 | ```\nclass Solution {\n int mod = 1_000_000_007;\n public int countRestrictedPaths(int n, int[][] edges) {\n List[] nei = new List[n+1];\n f | JJYZ | NORMAL | 2021-04-06T03:34:15.577322+00:00 | 2021-04-06T03:34:15.577354+00:00 | 170 | false | ```\nclass Solution {\n int mod = 1_000_000_007;\n public int countRestrictedPaths(int n, int[][] edges) {\n List<int[]>[] nei = new List[n+1];\n for(int i=1; i<=n; i++)\n nei[i] = new ArrayList<int[]>();\n for(int[] edge : edges){\n nei[edge[0]].add(new int[]{edge[1], edge[2]});\n nei[edge[1]].add(new int[]{edge[0], edge[2]});\n }\n int[] dis = new int[n+1];\n PriorityQueue<int[]> q = new PriorityQueue<int[]>((a,b)->(a[1]-b[1]));\n q.offer(new int[]{n, 0});\n int[] visited = new int[n+1];\n while(!q.isEmpty()){\n int[] cur = q.poll();\n if(visited[cur[0]] == 1)\n continue;\n dis[cur[0]] = cur[1];\n visited[cur[0]]=1;\n for(int[] next : nei[cur[0]])\n if(visited[next[0]] == 0)\n q.offer(new int[]{next[0], next[1]+cur[1]});\n }\n return dfs(1, n, dis, new HashMap(), nei);\n }\n \n public int dfs(int from, int to, int[] dis, HashMap<Integer, Integer> map, List<int[]>[] nei){\n if(from == to) return 1;\n if(map.containsKey(from)) return map.get(from);\n int res = 0;\n for(int[] next : nei[from])\n if(dis[next[0]]<dis[from])\n res = (res+dfs(next[0], to, dis, map, nei))%mod;\n map.put(from, res);\n return res;\n }\n} | 2 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ beats 100 100 using dijksta and dfs with memoization | c-beats-100-100-using-dijksta-and-dfs-wi-s3dn | \nclass Solution {\npublic:\n// Declaring variables gloabally so that we don\'t need to pass every time in function and we can directly access in dfs function\n | 18bce192 | NORMAL | 2021-03-11T17:05:49.376725+00:00 | 2021-03-27T16:59:26.168668+00:00 | 338 | false | ```\nclass Solution {\npublic:\n// Declaring variables gloabally so that we don\'t need to pass every time in function and we can directly access in dfs function\n unordered_map <int,vector <pair<int,int>>> m;\n vector <int> dist;\n vector <int> dp;\n int N;\n int MOD=1000000007;\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector <int> vis(n+1,0);\n dist.resize(n+1,INT_MAX);\n dp.resize(n+1,-1);\n dist[0]=0;\n N=n;\n for(auto i:edges)\n {\n m[i[0]].push_back({i[1],i[2]});\n m[i[1]].push_back({i[0],i[2]});\n }\n set <pair <int,int>> q;\n q.insert({0,n});\n dist[n]=0;\n while(!q.empty())\n {\n int u=q.begin()->second;\n q.erase(q.begin());\n vis[u]=1;\n for(auto p:m[u])\n {\n int v=p.first;\n int w=p.second;\n if(!vis[v])\n {\n if(dist[u]+w<dist[v])\n {\n dist[v]=dist[u]+w;\n q.insert({dist[v],v});\n }\n }\n }\n }\n return dfs(1);\n }\n \n int dfs(int u)\n {\n if(dp[u]!=-1)\n return dp[u];\n int ans=0;\n if(u==N)\n return 1;\n for(auto p:m[u])\n {\n int v=p.first;\n if(dist[v]<dist[u])\n ans=(ans+dfs(v))%MOD;\n }\n return dp[u]=ans;\n }\n};\n```\n\n | 2 | 1 | ['Dynamic Programming', 'Ordered Set', 'C++'] | 2 |
number-of-restricted-paths-from-first-to-last-node | [Python] Dijikstra(early stop) + graph DP, 1660ms | python-dijikstraearly-stop-graph-dp-1660-xg6w | Dijikstra to find the shortest distance from end node(n) to all other nodes. Early stop when node 1 is met. Since the nodes left unvisited will have larger dist | 18768897529b | NORMAL | 2021-03-07T04:52:05.872206+00:00 | 2021-03-07T04:52:05.872242+00:00 | 82 | false | Dijikstra to find the shortest distance from end node(n) to all other nodes. Early stop when node 1 is met. Since the nodes left unvisited will have larger distance to the end node. They won\'t be used to construct restricted paths.\n\nThen graph DP idea is that traversing from closer (to end node) nodes to further nodes. The number of paths for a node equals to sum of all its neighbors whose distance to end node are closer. \n\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n # construct the graph\n neigh = collections.defaultdict(list)\n for u,v,w in edges:\n neigh[u].append((v,w))\n neigh[v].append((u,w))\n \n # shortest path for all nodes to destination, using dijkstra:\n dist = collections.defaultdict(lambda : float(inf))\n heap = [(0,n)]\n while len(dist.keys()) < n:\n curDis, curNode = heapq.heappop(heap)\n if curNode in dist:\n continue\n \n for nei, w in neigh[curNode]:\n if nei not in dist:\n heapq.heappush(heap, ((curDis+w), nei))\n if curNode not in dist:\n dist[curNode] = curDis\n if curNode == 1:\n break\n \n # search from the closer to further nodes\n nodes = [(dist[i],i) for i in dist.keys()]\n nodes.sort()\n paths = collections.defaultdict(int)\n paths[n] = 1\n for _, node in nodes[1:]:\n path = 0\n for nei, _ in neigh[node]:\n path += paths[nei] if dist[nei] < dist[node] else 0 # to avoid the equal distance nodes\n path = int(path%(1e9+7))\n \n paths[node] = path\n if node == 1:\n return path\n \n return 0\n \n``` | 2 | 1 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Bellman-Ford (TLE) and SPFA (AC) | bellman-ford-tle-and-spfa-ac-by-claytonj-2mn1 | Synopsis:\n\nBellman-Ford results in TLE. SPFA is a natural progression from Bellman-Ford which only considers each next round of edge relaxations to be perfor | claytonjwong | NORMAL | 2021-03-07T04:00:23.912904+00:00 | 2021-03-19T21:41:28.545913+00:00 | 367 | false | **Synopsis:**\n\n[Bellman-Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) results in TLE. [SPFA](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) is a natural progression from [Bellman-Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) which only considers each next round of edge relaxations to be performed upon the candidates which can be potentially relaxed, ie. the current candidates `cur` are formulated from the previous candidates `pre`.\n\nOnce the distances `dist` from the source node `N` have been calculated, perform DFS + BT to explore all paths from `1..N` which are strictly monotonically decreasing in distance. Perform memoization to store the solutions to sub-problems to avoid TLE, and don\'t forget to mod the count `cnt` of these paths by `1e9 + 7`.\n\n---\n\n**Contest 231 Screenshare:**\n\n\n\n\n---\n\n**Bellman-Ford (TLE):**\n```\nlet countRestrictedPaths = (N, E, mod = Number(1e9 + 7), cnt = 0) => {\n let dist = Array(N + 1).fill(Infinity); // +1 for 1-based indexing, ie. the 0-th index isn\'t used\n dist[N] = 0; // source node is N, calc dist to source by relaxing edges N - 1 times\n let K = N - 1;\n while (K--) { // for N - 1 iterations: relax edges u->v and v->u of weight w\n E.forEach(([u, v, w]) => {\n if (dist[v] > dist[u] + w) dist[v] = dist[u] + w;\n if (dist[u] > dist[v] + w) dist[u] = dist[v] + w;\n });\n }\n let adj = new Map();\n E.forEach(([u, v, w]) => {\n if (!adj.has(u)) adj.set(u, new Set()); adj.set(u, adj.get(u).add(v));\n if (!adj.has(v)) adj.set(v, new Set()); adj.set(v, adj.get(v).add(u));\n });\n let m = new Map();\n let go = (u = 1, path = new Set(), cnt = 0) => {\n if (m.has(u))\n return m.get(u);\n if (u == N)\n return 1;\n path.add(u); // forward-tracking\n for (let v of adj.get(u))\n if (dist[u] > dist[v] && !path.has(v))\n cnt = (cnt + go(v, path)) % mod;\n path.delete(u); // back-tracking\n return m.set(u, cnt).get(u);\n };\n return go();\n};\n```\n\n**SPFA (AC):**\n```\nlet countRestrictedPaths = (N, E, mod = Number(1e9 + 7), cnt = 0) => {\n let adj = new Map();\n let key = (u, v) => `${u},${v}`;\n let cost = new Map();\n E.forEach(([u, v, w]) => {\n if (!adj.has(u)) adj.set(u, new Set()); adj.set(u, adj.get(u).add(v)); cost.set(key(u, v), w);\n if (!adj.has(v)) adj.set(v, new Set()); adj.set(v, adj.get(v).add(u)); cost.set(key(v, u), w);\n });\n let dist = Array(N + 1).fill(Infinity); // +1 for 1-based indexing, ie. the 0-th index isn\'t used\n dist[N] = 0; // calculate distance to source node N by relaxing current candidate edges which are formulated based upon the previous edge relaxations\n let cur = [N];\n while (cur.length) {\n let pre = [...cur]; cur = [];\n for (let u of pre)\n for (let v of adj.get(u))\n if (dist[v] > dist[u] + cost.get(key(u, v)))\n dist[v] = dist[u] + cost.get(key(u, v)), cur.push(v);\n }\n let m = new Map();\n let go = (u = 1, path = new Set(), cnt = 0) => {\n if (m.has(u))\n return m.get(u);\n if (u == N)\n return 1;\n path.add(u); // forward-tracking\n for (let v of adj.get(u))\n if (dist[u] > dist[v] && !path.has(v))\n cnt = (cnt + go(v, path)) % mod;\n path.delete(u); // back-tracking\n return m.set(u, cnt).get(u);\n };\n return go();\n};\n``` | 2 | 0 | [] | 1 |
number-of-restricted-paths-from-first-to-last-node | C++ | Dijkstra's + DFS + Memoization/DP | Easy to Understand | c-dijkstras-dfs-memoizationdp-easy-to-un-vdat | Intuition
use Dijkstra's Algorithm to find the minimum distance from node n to all the other nodes
after calculating the minimum distances traverse the graph st | ghozt777 | NORMAL | 2025-04-09T19:58:22.226693+00:00 | 2025-04-09T19:59:43.998363+00:00 | 12 | false | # Intuition
- use [Dijkstra's Algorithm](https://cp-algorithms.com/graph/dijkstra.html) to find the minimum distance from node `n` to all the other nodes
- after calculating the minimum distances traverse the graph starting from node `1` to node `n`
- the only catch is that if you are currently on node `u` and want to travel to node `v` then `distance[v]` must be less than `distance[u]` aka `distance[v] < distance[u]` to travel `u -> v` , use dfs to traverse the graph.
# Code
```cpp []
class Solution {
using pi = pair<int,int> ;
using ll = long long ;
vector<int> dp ;
vector<bool> vis ;
ll MOD = 1e9 + 7 ;
vector<int> dijkstras(vector<vector<pi>> &adj){
const int n = adj.size() ;
vector<int> dist(n,INT_MAX) ;
dist[n - 1] = 0 ;
priority_queue<pi,vector<pi>,greater<pi>> pq ;
pq.push({0,n-1}) ;
while(!pq.empty()){
auto [d,u] = pq.top() ;
pq.pop() ;
if(d > dist[u]) continue ;
for(auto [v,w] : adj[u]){
if(dist[v] > dist[u] + w){
dist[v] = dist[u] + w ;
pq.push({dist[v],v}) ;
}
}
}
return dist ;
}
ll dfs(vector<vector<pi>> &adj, vector<int> &dist, int u){
if(dp[u] != -1) return dp[u] ;
if(u == adj.size() - 1){
return 1 ;
}
vis[u] = true ;
ll curr = 0 ;
for(auto [v,w] : adj[u]){
if(!vis[v] && dist[v] < dist[u]) curr = (curr + dfs(adj,dist,v)) % MOD ;
}
vis[u] = false ;
return dp[u] = curr ;
}
public:
int countRestrictedPaths(int n, vector<vector<int>>& edges) {
dp.resize(n,-1) ;
vis.resize(n,false) ;
vector<vector<pi>> adj(n) ;
for(auto &e : edges){
int u = e[0] , v = e[1] , w = e[2] ;
--u , --v ;
adj[u].push_back({v,w}) ;
adj[v].push_back({u,w}) ;
}
vector<int> dist = dijkstras(adj) ;
return dfs(adj,dist,0) ;
}
};
``` | 1 | 0 | ['Dynamic Programming', 'Graph', 'Memoization', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Very Easy C++ Problem: Just Needed One Night to Understand | very-easy-c-problem-just-needed-one-nigh-5583 | Code | Yash_Bhoomkar | NORMAL | 2025-02-18T03:48:08.044822+00:00 | 2025-02-18T03:48:08.044822+00:00 | 80 | false |
# Code
```cpp []
#define P pair<int,int>
const int MOD = 1e9+7;
class Solution
{
vector<vector<int>> paths;
vector<int> dist;
int dfs(vector<vector<P>>& adj, int current_node, vector<int>& visited, int& n, vector<int>& current_path , vector<int>& dp)
{
// visited[current_node] = 1;
if(current_node == n)
{
return 1;
}
if(dp[current_node] != -1)
{
return dp[current_node];
}
int meow = 0;
for(auto it : adj[current_node])
{
if(!visited[it.second] && dist[it.second] < dist[current_node])
{
current_path.push_back(it.second);
meow = (meow + dfs(adj , it.second , visited , n , current_path , dp)) % MOD;
current_path.pop_back();
}
}
//visited[current_node] = 0;
return dp[current_node] = meow;
}
public:
int countRestrictedPaths(int n, vector<vector<int>>& edges)
{
vector<vector<P>> adj(n+1);
for(auto it : edges)
{
int u = it[0];
int v = it[1];
int wt = it[2];
adj[u].push_back({wt, v});
adj[v].push_back({wt, u});
}
dist = vector<int>(n+1, INT_MAX);
priority_queue<P, vector<P>, greater<P>> pq;
dist[n] = 0;
pq.push({0, n});
while(!pq.empty())
{
auto top = pq.top();
pq.pop();
int currDist = top.first;
int node = top.second;
if(currDist > dist[node]) continue;
for(auto each : adj[node])
{
int edgeWt = each.first;
int neighbor = each.second;
if(currDist + edgeWt < dist[neighbor])
{
dist[neighbor] = currDist + edgeWt;
pq.push({dist[neighbor], neighbor});
}
}
}
vector<int> dp(n+1 , -1);
vector<int> visited(n+1 , 0);
vector<int> current_path = {1};
dfs(adj , 1 , visited , n , current_path , dp);
return dp[1] % MOD;
}
};
``` | 1 | 0 | ['Dynamic Programming', 'Graph', 'Shortest Path', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | DYNAMIC PROGRAMMING + DIJKSTRA ALGORITHM | dynamic-programming-dijkstra-algorithm-b-ak0w | just find the minimum distance from nth node to all other nodes and the do a dfs with memoization to count all the restricted partsComplexity
Time complexity:O( | samman_varshney | NORMAL | 2025-02-10T14:36:41.798297+00:00 | 2025-02-10T14:36:41.798297+00:00 | 64 | false | just find the minimum distance from nth node to all other nodes and the do a dfs with memoization to count all the restricted parts
# Complexity
- Time complexity:O(ElogV)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(E+V)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int dfs(ArrayList<ArrayList<int[]>> adj, int[] dist, int idx, int[] dp){
if(idx == 1)
return 1;
if(dp[idx] != -1)return dp[idx];
int count = 0;
for(int[] x : adj.get(idx)){
if(dist[x[1]] > dist[idx])
count = (count + dfs(adj, dist, x[1], dp)) % 1000000007;
}
return dp[idx] = count;
}
public int countRestrictedPaths(int n, int[][] edges) {
ArrayList<ArrayList<int[]>> adj = new ArrayList<>();
for(int i=0;i<=n;i++)
adj.add(new ArrayList<>());
for(int x[] : edges){
adj.get(x[0]).add(new int[]{x[2], x[1]});
adj.get(x[1]).add(new int[]{x[2], x[0]});
}
PriorityQueue<int[]> q = new PriorityQueue<>((a, b)->(a[0]-b[0]));
q.add(new int[]{0, n});
int[] dist = new int[n+1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[n] = 0;
while(!q.isEmpty()){
int node = q.peek()[1];
int currDist = q.poll()[0];
if (currDist > dist[node]) continue;
for(int[] x: adj.get(node)){
int nextDist = currDist+x[0];
if(nextDist < dist[x[1]]){
dist[x[1]] = nextDist;
q.add(new int[]{dist[x[1]], x[1]});
}
}
}
// System.out.println(Arrays.toString(dist));
int[] dp = new int[n+1];
Arrays.fill(dp, -1);
int res = dfs(adj, dist, n, dp);
return res;
}
}
```
if you have any doubt, then do comment it, i will help you out. | 1 | 0 | ['Dynamic Programming', 'Graph', 'Heap (Priority Queue)', 'Shortest Path', 'Java'] | 0 |
number-of-restricted-paths-from-first-to-last-node | O(eloge) Time Simple Dijkstra Solution || Commented Code | oeloge-time-simple-dijkstra-solution-com-b4lg | Code | ammar-a-khan | NORMAL | 2025-01-25T11:06:33.277075+00:00 | 2025-01-25T11:06:33.277075+00:00 | 82 | false | # Code
```cpp
int helper(int node, vector<vector<pair<int, int>>> &g, vector<int> &dist, vector<int> &dp){ //simply travels from 1->n cuz dist constraint makes the graph a DAG
if (node == g.size() - 1){ return 1; }
if (dp[node] == -1){ //compute if not done already
int sum = 0;
for (int i = 0; i < g[node].size(); ++i){
if (dist[g[node][i].first] < dist[node]){
sum = (sum + helper(g[node][i].first, g, dist, dp))%1000000007;
}
}
dp[node] = sum;
}
return dp[node];
}
int countRestrictedPaths(int n, vector<vector<int>>& edges){
vector<vector<pair<int, int>>> g(n); //graph
for (int i = 0; i < edges.size(); ++i){
g[edges[i][0] - 1].push_back({edges[i][1] - 1, edges[i][2]});
g[edges[i][1] - 1].push_back({edges[i][0] - 1, edges[i][2]});
}
vector<int> dist(n, INT_MAX); //stores dist b/w node i & n, using dijkstra
dist[n - 1] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, n - 1});
while (pq.size() > 0){
int currDist = pq.top().first, node = pq.top().second;
pq.pop();
for (int i = 0; i < g[node].size(); ++i){
int neighbor = g[node][i].first, toNeighbor = g[node][i].second;
if (currDist + toNeighbor < dist[neighbor]){
dist[neighbor] = currDist + toNeighbor;
pq.push({dist[neighbor], neighbor});
}
}
}
vector<int> dp(n, -1); //1D dp
return helper(0, g, dist, dp);
}
``` | 1 | 0 | ['Dynamic Programming', 'Graph', 'Topological Sort', 'Heap (Priority Queue)', 'Shortest Path', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | DijKstra + DP in C++ | dijkstra-dp-in-c-by-wait_watch-4ftm | \n#define pii pair<long,int>\n# define mod 1000000007\nclass Solution {\npublic:\n \n long DFS(int x, int n,vector<long>&dp , vector<long>&dis, vector<pa | wait_watch | NORMAL | 2024-07-20T11:01:14.027543+00:00 | 2024-07-20T11:01:14.027576+00:00 | 3 | false | ```\n#define pii pair<long,int>\n# define mod 1000000007\nclass Solution {\npublic:\n \n long DFS(int x, int n,vector<long>&dp , vector<long>&dis, vector<pair<int,long>>*g){\n if(x==n)\n return 1;\n else if(dp[x]!=-1)\n return dp[x];\n long ans =0;\n for(int i=0;i<g[x].size();i++){\n int v = g[x][i].first;\n if( dis[x]>dis[v]){\n ans = (ans+ DFS(v,n, dp, dis, g))%mod;\n }\n }\n dp[x] = ans;\n return ans;\n }\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<long>dis(n+1, INT_MAX);\n vector<pair<int,long>>g[n+1];\n for(int i=0;i<edges.size();i++){\n g[edges[i][0]].push_back({edges[i][1],edges[i][2]});\n g[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n priority_queue<pii,vector<pii>, greater<pii>>pq;\n pq.push({0,n});\n dis[n]=0;\n while(!pq.empty()){\n pii temp = pq.top();\n pq.pop();\n int u = temp.second;\n for(int i =0;i<g[u].size();i++){\n int v = g[u][i].first;\n long wt = g[u][i].second;\n if(dis[u]+wt<dis[v]){\n dis[v]=wt+dis[u];\n pq.push({dis[v],v});\n }\n }\n }\n\n vector<long>dp(n+1,-1);\n return DFS(1,n,dp,dis,g);\n }\n};\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | clean short code using heap in python | clean-short-code-using-heap-in-python-by-n5wd | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Akuma-Greyy | NORMAL | 2024-06-20T11:32:25.899915+00:00 | 2024-06-20T11:32:25.899938+00:00 | 210 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n\n adjl = {}\n for edge in edges:\n if edge[0] not in adjl:\n adjl[edge[0]] = { edge[1] : edge[2] }\n else:\n adjl[edge[0]][edge[1]] = edge[2]\n if edge[1] not in adjl:\n adjl[edge[1]] = { edge[0] : edge[2] }\n else:\n adjl[edge[1]][edge[0]] = edge[2]\n shortest = {}\n minHeap = []\n heapq.heappush(minHeap,(0,n))\n while minHeap and len(shortest)!=n:\n k=heapq.heappop(minHeap)\n if k[1] in shortest:\n continue\n shortest[k[1]]=k[0]\n\n for neighbour,weight in adjl[k[1]].items():\n if neighbour not in shortest:\n heapq.heappush(minHeap,(weight + k[0],neighbour)) \n no_of_paths = [0]*n\n no_of_paths[n-1] = 1\n heap = []\n visited = set()\n for i in range(n):\n heapq.heappush(heap,(shortest[i+1],i+1))\n while heap:\n p = heapq.heappop(heap)\n for k,_ in adjl[p[1]].items():\n if p[0]<shortest[k]:\n no_of_paths[k-1] += no_of_paths[p[1]-1] \n return no_of_paths[0]%(10**9+7)\n\n \n``` | 1 | 0 | ['Dynamic Programming', 'Graph', 'Topological Sort', 'Heap (Priority Queue)', 'Shortest Path', 'Python3'] | 0 |
number-of-restricted-paths-from-first-to-last-node | BFS + Dijkstra + Topological Sort Java Solution | bfs-dijkstra-topological-sort-java-solut-1vjb | Intuition\nAll the restricted path belongs to a DAG, topological sort is a straightforward solution. Calculating the number of paths at the final step requires | ericwangirvine | NORMAL | 2024-03-06T01:27:53.730376+00:00 | 2024-03-06T01:27:53.730429+00:00 | 92 | false | # Intuition\nAll the restricted path belongs to a DAG, topological sort is a straightforward solution. Calculating the number of paths at the final step requires a bit of thinking, topological sort helps in this case since before moving to the next node, it naturally waits for all the incoming edges to finish counting.\n\n# Approach\n- Build the complete graph\n- Dijkstra to get the shortest path from all nodes to `last` node\n- Build the `DAG` from `start` to `last` with all the related restricted paths\n- Topological sort on the `DAG` generated from last step and count paths for each node\n\n# Complexity\n- Time complexity:\n$$O(V + ElogV)$$ bounded by dijkstra\n`E` -> all the nodes\n`V` -> all the edges\n\n- Space complexity:\n$$O(V + E)$$\n\n# Code\n```java []\nclass Solution {\n class Node {\n int id;\n Map<Integer, Integer> neighbors;\n public Node(int id) {\n this.id = id;\n this.neighbors = new HashMap<>();\n }\n }\n private final int MOD = (int)1e9 + 7;\n private Node[] nodes;\n private Map<Integer, List<Integer>> adj;\n private int[] in, distance;\n public int countRestrictedPaths(int n, int[][] edges) {\n buildCompleteGraph(edges, n);\n getShortestPath(n);\n buildRestrictedPathGraph(0, n - 1);\n return topologicalSort(n);\n }\n\n private int topologicalSort(int n) {\n long[] ways = new long[n];\n ways[0] = 1;\n Queue<Integer> queue = new LinkedList<>();\n queue.offer(0);\n\n while (!queue.isEmpty()) {\n int cur = queue.poll();\n for (int neighbor: adj.getOrDefault(cur, new ArrayList<>())) {\n ways[neighbor] = (ways[neighbor] + ways[cur]) % MOD;\n if (--in[neighbor] == 0) queue.offer(neighbor);\n }\n }\n\n return (int)ways[n - 1];\n }\n\n private void buildCompleteGraph(int[][] edges, int n) {\n this.nodes = new Node[n];\n\n for (int i = 0; i < n; i++) {\n nodes[i] = new Node(i);\n }\n\n for (int[] edge: edges) {\n int from = edge[0] - 1, to = edge[1] - 1, cost = edge[2];\n nodes[from].neighbors.put(to, cost);\n nodes[to].neighbors.put(from, cost);\n }\n }\n\n private void getShortestPath(int n) {\n this.distance = new int[n];\n Arrays.fill(distance, Integer.MAX_VALUE);\n distance[n - 1] = 0;\n boolean[] visited = new boolean[n];\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);\n pq.offer(new int[]{n - 1, 0});\n while (!pq.isEmpty()) {\n int[] cur = pq.poll();\n visited[cur[0]] = true;\n if (cur[1] > distance[cur[0]]) continue;\n for (int neighbor: nodes[cur[0]].neighbors.keySet()) {\n if (visited[neighbor]) continue;\n int newD = cur[1] + nodes[cur[0]].neighbors.get(neighbor);\n if (newD >= distance[neighbor]) continue;\n distance[neighbor] = newD;\n pq.offer(new int[]{neighbor, newD});\n }\n }\n }\n\n private void buildRestrictedPathGraph(int src, int dst) {\n int n = distance.length;\n adj = new HashMap<>();\n in = new int[n];\n Queue<Integer> queue = new LinkedList<>();\n queue.offer(src);\n boolean[] visited = new boolean[n];\n visited[src] = true;\n while (!queue.isEmpty()) {\n int cur = queue.poll();\n if (cur == dst) continue;\n for (int neighbor: nodes[cur].neighbors.keySet()) {\n if (distance[neighbor] >= distance[cur]) continue;\n in[neighbor]++;\n adj.computeIfAbsent(cur, a -> new ArrayList<>()).add(neighbor);\n if (visited[neighbor]) continue;\n queue.offer(neighbor);\n visited[neighbor] = true;\n }\n }\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra+DFS+Memoization beats 100% python3 | dijkstradfsmemoization-beats-100-python3-kfho | Explanation of the Soultion: \nWe need to find the number of paths between 1st to nth node in which the shortest path from the end node to each of the nodes of | jaidev2 | NORMAL | 2023-12-24T09:01:08.761373+00:00 | 2023-12-24T09:01:08.761398+00:00 | 3 | false | Explanation of the Soultion: \nWe need to find the number of paths between 1st to nth node in which the **shortest path from the end node** to each of the nodes of the path is in **strictly decreasing order**, for an example\nlets say there exist a path where n=5: 1->3->5, now lets say shortest path from 1 to 5 is 3 and shortest path from 3 to 5 is 2 then this is a valid restricted path because 3>2.\n\nNow, let us divide the problem in two parts:\n1. find the shortest path of each node from the end node (using dijkstra)\n2. do a depth first search from node n, now as this is an exhaustive search or simply figuring out all the paths from n to 1 which are restricted, there is a possibility that we may visit a node which was already visited previously hence we will end up calculating the path again. Now to tackle this, we can further optimise it using memoization.\nBelow is the code:\n```\nclass Solution:\n def dijkstra(self,start,graph,distanceArr):\n distanceArr[start]=0\n queue=[(0,start)]\n heapq.heapify(queue)\n while queue:\n wt,u=heapq.heappop(queue)\n if wt>distanceArr[u]:continue #to only check min distance node in priority queue\n for v,w in graph[u]:\n if distanceArr[v]<=distanceArr[u]+w:continue\n distanceArr[v]=distanceArr[u]+w\n heapq.heappush(queue,(distanceArr[v],v))\n return 0\n \n def dfs(self,u,graph,distanceArr,dp):\n if u==1:return 1\n if dp[u]!=-1:return dp[u]\n ans=0\n for v,w in graph[u]:\n if distanceArr[v]>distanceArr[u]:\n ans=(ans+self.dfs(v,graph,distanceArr,dp))%self.mod\n dp[u]=ans\n return ans\n \n \n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph=defaultdict(lambda:[])\n dp=[-1]*(n+1)\n self.mod=1000_000_007\n for u,v,w in edges:\n graph[u].append((v,w))\n graph[v].append((u,w))\n distanceArr=[float(\'inf\')]*(n+1)\n self.dijkstra(n,graph,distanceArr)\n return self.dfs(n,graph,distanceArr,dp)\n\n```\n\nComplexity:\n Time: O(M * logN), where M is number of edges, N is number of nodes.\n Space: O(M + N)\n | 1 | 0 | ['Depth-First Search', 'Memoization'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Easy C++ Solution | easy-c-solution-by-astha_jj-hghw | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | astha_jj | NORMAL | 2023-10-28T11:39:17.160422+00:00 | 2023-10-28T11:39:17.160441+00:00 | 109 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N){dfs}+O(V+E){djksta}\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n//In this question first we need to find the minimum weight(smiliar to minimum distance) it takes to reach the end node from every node\n// after that we traverse from first node in search of a valid path and we keep a count and return it\nclass Solution {\npublic:\n const int MOD = 1e9 + 7;\n\n int dfs(int node, int end, vector<int>& dis, unordered_map<int, vector<pair<int, int>>>& adj, vector<int>& dp) {\n if (node == end) {\n return dp[node]=1; // when we reach the final destination we retrun 1 which signifies a path found\n }\n\n if(dp[node]!=-1)return dp[node];\n\n int count = 0;\n\n for (auto u : adj[node]) {\n if (dis[node] > dis[u.first]) { // we only move forward when condition is satisfied\n int path = dfs(u.first, end, dis, adj, dp);\n count = (count + path) % MOD; // Update count with modular arithmetic.\n }\n }\n\n return dp[node]=count;\n }\n\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n unordered_map<int, vector<pair<int, int>>> adj;\n\n for (int i = 0; i < edges.size(); i++) {\n int u = edges[i][0];\n int v = edges[i][1];\n int wt = edges[i][2];\n\n adj[u].push_back({v, wt});\n adj[v].push_back({u, wt}); // Assuming an undirected graph\n }\n\n vector<int> dis(n + 1, INT_MAX);\n dis[n] = 0;\n\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n pq.push({0, n}); // Push the starting node with distance 0\n\n while (!pq.empty()) {\n int dist = pq.top().first;\n int node = pq.top().second;\n pq.pop();\n\n for (auto u : adj[node]) {\n int adjNode = u.first;\n int adjDist = u.second;\n\n if (dis[adjNode] > dist + adjDist) {\n dis[adjNode] = dist + adjDist;\n pq.push({dis[adjNode], adjNode});\n }\n }\n }\n // calling dfs from node 1 to last node \n //this will return no of restricated path\n vector<int> dp(n + 1, -1); // dp array\n int i = 1; //starting from node 1\n return dfs(i, n, dis, adj, dp);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Shortest Path', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra + DFS with DP || C++ || explained | dijkstra-dfs-with-dp-c-explained-by-avi_-bpzg | First find the minimum distance to each node from the last node. Using dijkstra algorithm\n- Using DFS go to each path and check if dist[adjnode] < dist[node]\n | avi_1344 | NORMAL | 2023-08-23T17:16:03.727464+00:00 | 2023-08-23T17:16:03.727494+00:00 | 62 | false | - First find the minimum distance to each node from the last node. Using dijkstra algorithm\n- Using DFS go to each path and check if ```dist[adjnode] < dist[node]```\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n vector<int> dijkstra(int n, vector<vector<pair<int,int>>> &adj){\n vector<int> dist(n+1, INT_MAX);\n priority_queue<pair<int,int>, vector<pair<int, int>>, greater<pair<int,int>>> pq;\n dist[n] = 0;\n pq.push({0, n});\n\n while(!pq.empty()){\n int node = pq.top().second;\n int d = pq.top().first;\n pq.pop();\n\n for(auto it: adj[node]){\n int adjnode = it.first;\n int wt = it.second;\n if(d + wt < dist[adjnode]){\n dist[adjnode] = d + wt;\n pq.push({dist[adjnode], adjnode});\n }\n }\n }\n return dist;\n }\n\n int dfs(int node, vector<vector<pair<int,int>>> &adj, int n, vector<bool> &vis, vector<int> &dist, vector<int> &dp){\n if(node == n){\n return 1;\n }\n\n if(dp[node] != -1){\n return dp[node];\n }\n\n vis[node] = 1;\n\n int ans = 0;\n for(auto it : adj[node]){\n int adjnode = it.first;\n if(!vis[adjnode] && dist[adjnode] < dist[node]){\n ans = ans%mod + dfs(adjnode, adj, n, vis, dist, dp)%mod;\n }\n }\n\n vis[node] = 0;\n return dp[node] = ans%mod;\n }\n\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int,int>>> adj(n+1);\n for(auto it: edges){\n adj[it[0]].push_back({it[1],it[2]});\n adj[it[1]].push_back({it[0],it[2]});\n }\n\n vector<int> dist = dijkstra(n, adj);\n vector<bool> pathvis(n+1, 0);\n vector<int> dp(n+1, -1);\n\n return dfs(1, adj, n, pathvis, dist, dp);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Graph', 'Shortest Path', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | DP + Dijkstra + DFS = SOLUTION | dp-dijkstra-dfs-solution-by-whoisslimsha-cek5 | \n\n# Code\n\nclass Solution {\npublic:\n int mod = 1e9+7;\n // simple dijkstra to find shortest distance from node n \n vector<int> dijkstra(vector<ve | whoisslimshady | NORMAL | 2023-08-10T08:20:30.903995+00:00 | 2023-08-10T08:20:30.904014+00:00 | 9 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9+7;\n // simple dijkstra to find shortest distance from node n \n vector<int> dijkstra(vector<vector<pair<int,int>>>&adj, int n){\n\t priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int>>> pq;\n vector<int> distTo(n+1,INT_MAX);\n pq.push({0,n});\n distTo[n] = 0;\n while(!pq.empty()){\n int weight = pq.top().first;\n int node = pq.top().second;\n pq.pop();\n for(auto it: adj[node]){\n int adjNode = it.first;\n int edgW = it.second;\n if(weight + edgW < distTo[adjNode]){\n distTo[adjNode] = weight + edgW;\n pq.push( {distTo[adjNode],adjNode} );\n }\n }\n }\n return distTo;\n }\n\n // dfs to check which path satisfying the conditions \n int dfs(vector<vector<pair<int,int>>>&adj, vector<int>& dp, vector<int>& dist, int src){\n int sum =0;\n if(src==1) return 1;\n if(dp[src]!=-1) return dp[src];\n\n for(auto adjNode:adj[src]){\n int costFromIthNode = dist[src];\n int costFromNextNode = dist[adjNode.first];\n if(costFromNextNode > costFromIthNode) // condition satisfied \n sum = (sum% mod + dfs(adj,dp,dist,adjNode.first)%mod) % mod;\n // dont be confused with the condition that in question it was written distanceToLastNode(zi) > distanceToLastNode(zi+1) \n // but here is am doing opposite that\'s because i am traversing the graph the last \n }\n return dp[src] = sum% mod;\n\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int,int>>>graph(n+1);\n for(auto it:edges){\n graph[it[0]].push_back({it[1],it[2]});\n graph[it[1]].push_back({it[0],it[2]});\n }\n vector<int>dist = dijkstra(graph,n);\n vector<int>dp(n+1,-1);\n return dfs(graph,dp,dist,n);\n }\n};\n``` | 1 | 1 | ['Dynamic Programming', 'Graph', 'C++'] | 1 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra + DFS approach | Java solution | Clean Code | dijkstra-dfs-approach-java-solution-clea-fz1y | Complexity\nLet v = number of nodes\ne = number of adges\n- Time complexity: $O((v + e)\log v)$\n Add your time complexity here, e.g. O(n) \n\n- Space complexit | vrutik2809 | NORMAL | 2023-04-19T19:39:36.696300+00:00 | 2023-04-19T19:39:36.696340+00:00 | 134 | false | # Complexity\nLet `v = number of nodes`\n`e = number of adges`\n- Time complexity: $O((v + e)\\log v)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(v)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java\nclass Solution {\n List<List<int[]>> adj;\n int vals[];\n int MOD = (int)1e9 + 7;\n int cnts[];\n int v;\n int[] dijkstra(int n,int s){\n int dist[] = new int[n];\n Arrays.fill(dist,Integer.MAX_VALUE);\n dist[s] = 0;\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] - b[1]);\n pq.add(new int[]{s,0});\n for(;!pq.isEmpty();){\n var a = pq.poll();\n for(var c:adj.get(a[0])){\n if(dist[c[0]] > a[1] + c[1]){\n dist[c[0]] = a[1] + c[1];\n pq.add(new int[]{c[0],dist[c[0]]});\n }\n }\n }\n return dist;\n } \n int dfs(int n,int prev){\n if(vals[n] >= prev) return 0;\n if(cnts[n] != -1) return cnts[n];\n if(n == v - 1) return 1;\n int ans = 0;\n for(var c:adj.get(n)){\n ans = (ans + dfs(c[0],vals[n])) % MOD;\n }\n return cnts[n] = ans % MOD;\n }\n public int countRestrictedPaths(int n, int[][] edges) {\n adj = new ArrayList<>();\n cnts = new int[n];\n Arrays.fill(cnts,-1);\n v = n;\n for(int i = 0;i < n;i++){\n adj.add(new ArrayList<>());\n }\n for(var e:edges){\n adj.get(e[0] - 1).add(new int[]{e[1] - 1,e[2]});\n adj.get(e[1] - 1).add(new int[]{e[0] - 1,e[2]});\n }\n vals = dijkstra(n,n - 1);\n return dfs(0,Integer.MAX_VALUE) % MOD;\n }\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Java'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Easy Video Walkthrough | easy-video-walkthrough-by-bnchn-0w33 | Video Walkthrough\n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n G = [[] for _ in range(n+1)]\n | bnchn | NORMAL | 2022-11-02T16:59:29.313718+00:00 | 2022-11-02T16:59:29.313765+00:00 | 99 | false | [Video Walkthrough](https://youtu.be/hXrcIbzaVHQ)\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n G = [[] for _ in range(n+1)]\n SRC = n\n pq = [(0,SRC)]\n \n for u,v,w in edges: G[u].append((v,w)), G[v].append((u,w))\n distToLastNode = [float(\'inf\')] * (n+1)\n \n while pq:\n w_u, u = heapq.heappop(pq)\n if w_u > distToLastNode[u]: continue\n distToLastNode[u] = w_u\n for v, w_v in G[u]:\n if w_u + w_v < distToLastNode[v]:\n distToLastNode[v] = w_u + w_v\n heapq.heappush(pq,(w_u + w_v, v))\n D = [0] * (n+1)\n D[n] = 1\n def dfs(u):\n if D[u]: return D[u]\n for v,_ in G[u]:\n if distToLastNode[v] < distToLastNode[u]:\n D[u] += dfs(v)\n return D[u] \n return dfs(1) % ( 10 ** 9 + 7)\n```\n \n | 1 | 0 | ['Python'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra and memo, java solution, beats 99% | dijkstra-and-memo-java-solution-beats-99-acro | \nclass Solution {\n Integer[]memo;\n static final int INF = Integer.MAX_VALUE;\n static final int MOD = (int)(1E9) + 7;\n public int countRestricte | yasmine-ya | NORMAL | 2022-09-28T23:06:42.699579+00:00 | 2022-09-28T23:51:16.437662+00:00 | 336 | false | ```\nclass Solution {\n Integer[]memo;\n static final int INF = Integer.MAX_VALUE;\n static final int MOD = (int)(1E9) + 7;\n public int countRestrictedPaths(int n, int[][] edges) {\n List<int[]>[]graph = new ArrayList[n];\n memo = new Integer[n];\n int[]dis = new int[n];\n for(int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n for(int[]e : edges){\n graph[e[0]-1].add(new int[]{e[1]-1,e[2]});\n graph[e[1]-1].add(new int[]{e[0]-1,e[2]});\n }\n Arrays.fill(dis, INF);\n dis[n - 1] = 0;\n Queue<int[]> q = new PriorityQueue<int[]>((a,b)->(a[1] - b[1]));\n q.add(new int[]{n - 1, 0});\n while(!q.isEmpty()){\n int[]node = q.poll();\n int pos = node[0];\n int d = node[1];\n for(int[] u : graph[pos]){\n int next = u[0];\n int medium = u[1];\n if(medium + d < dis[next]){\n dis[next] = d + medium;\n q.add(new int[]{next, medium + d});\n }\n } \n }\n \n memo[n-1] = 1;\n \n return dfs(0, graph, dis);\n }\n private int dfs(int node,List<int[]>[]graph, int[]dis){\n if(memo[node] != null) {\n return memo[node];\n }\n long ans = 0;\n for(int[]k : graph[node]){\n if(dis[k[0]] < dis[node]){\n ans += dfs(k[0], graph, dis);\n }\n }\n memo[node] = (int)(ans % MOD);\n return memo[node];\n }\n}\n``` | 1 | 0 | ['Memoization'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Elegant. Dijktra's Algorithm and Dynamic Programming | elegant-dijktras-algorithm-and-dynamic-p-xfbm | \nimport math\nfrom heapq import heapify, heappop as hpop, heappush as hpush\nclass Solution:\n # O((|E| + |V|) * log(V)) Time and O(V + E) Space\n def co | kunal5042 | NORMAL | 2022-08-13T19:00:19.517363+00:00 | 2022-08-13T19:00:19.517393+00:00 | 105 | false | ```\nimport math\nfrom heapq import heapify, heappop as hpop, heappush as hpush\nclass Solution:\n # O((|E| + |V|) * log(V)) Time and O(V + E) Space\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n mod = (10**9) + 7\n graph = [set() for _ in range(n+1)]\n distances = [math.inf] * (n + 1)\n distances[n] = 0\n \n for source, dest, weight in edges:\n graph[source].add((weight, dest))\n graph[dest].add((weight, source))\n \n\n unexplored = [(0, n)]\n heapify(unexplored)\n explored = set()\n \n # dynamic-programming\n # at every index of ways, where index represents the node-id\n # we will store the number of ways we can reach this node\n # from node-1, with condition node-1\'s distance from node-n\n # is greater than this node\'s distance from node-n\n ways = [0] * (n+1)\n ways[n] = 1\n \n # dijkstra\'s algorithm\n # we are calculating shortest distance of each node\n # from node-n\n # and, along with that we are calculating number of restricted paths\n # from node-1 to node-n in bottom-up fashion\n while len(unexplored) != 0:\n weight, node = hpop(unexplored)\n \n if node in explored: continue\n explored.add(node)\n \n for adj_weight, adj_node in graph[node]:\n if adj_node in explored: continue\n \n new_weight = adj_weight + weight\n \n # update shortest-distance\n if new_weight < distances[adj_node]:\n distances[adj_node] = new_weight\n hpush(unexplored, (new_weight, adj_node))\n \n # update the number of ways/paths\n # we know that we have already explored node\n # so, we can use it\'s precomputed distance\n if distances[adj_node] > distances[node]:\n ways[adj_node] += ways[node]\n \n return ways[1] % mod\n \n\n``` | 1 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Fast Easy JS Solution | dijkstras + dfs + dp | 70% faster | fast-easy-js-solution-dijkstras-dfs-dp-7-slcg | \nvar countRestrictedPaths = function(n, edges) {\n const g = Array.from({ length: n + 1}, () => []);\n for(let [a, b, c] of edges) {\n g[a].push([ | nontoxic | NORMAL | 2022-06-19T05:42:31.756780+00:00 | 2022-06-19T05:42:31.756831+00:00 | 127 | false | ```\nvar countRestrictedPaths = function(n, edges) {\n const g = Array.from({ length: n + 1}, () => []);\n for(let [a, b, c] of edges) {\n g[a].push([b, c]);\n g[b].push([a, c]);\n }\n // do dijkstras to find shortest path from n to all nodes\n const dis = new Array(n + 1).fill(Infinity);\n dis[n] = 0;\n const dijkstra = () => {\n const heap = new MinPriorityQueue({ priority: (x) => x[1] });\n heap.enqueue([n, 0]);\n while(heap.size()) {\n const [node, cost] = heap.dequeue().element;\n for(let [nextNode, w] of g[node]) {\n const totalCost = cost + w;\n if(dis[nextNode] > totalCost) {\n dis[nextNode] = totalCost;\n heap.enqueue([nextNode, totalCost]);\n }\n }\n }\n }\n dijkstra();\n \n // do dfs from 1 having path always lesser dist\n let rPaths = 0;\n const MOD = 1000000007;\n const dp = new Array(n + 1).fill(-1);\n const dfs = (curr = 1, rCost = dis[1]) => {\n if(curr == n) return 1;\n if(dp[curr] != -1) return dp[curr];\n \n let op = 0;\n for(let [n, w] of g[curr]) {\n if(dis[n] < rCost) {\n op = (op + dfs(n, dis[n])) % MOD;\n }\n }\n \n return dp[curr] = op;\n }\n return dfs();\n};\n``` | 1 | 0 | ['JavaScript'] | 1 |
number-of-restricted-paths-from-first-to-last-node | [C++] Dijkstra + DP + DFS | c-dijkstra-dp-dfs-by-makhonya-9tix | \nclass Solution {\npublic:\n int MOD = 1e9 + 7;\n unordered_map<int, vector<pair<int, int>>> hash;\n int countRestrictedPaths(int n, vector<vector<int | makhonya | NORMAL | 2022-06-08T02:58:31.989359+00:00 | 2022-06-08T02:58:31.989395+00:00 | 219 | false | ```\nclass Solution {\npublic:\n int MOD = 1e9 + 7;\n unordered_map<int, vector<pair<int, int>>> hash;\n int countRestrictedPaths(int n, vector<vector<int>>& e) {\n for(auto& a: e){\n hash[a[0]].push_back({a[1], a[2]});\n hash[a[1]].push_back({a[0], a[2]});\n }\n vector<int> dist(n + 1, INT_MAX);\n vector<int> memo(n + 1, -1);\n dist[n] = 0;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n pq.push({0, n});\n while(!pq.empty()){\n auto [cost, node] = pq.top();\n pq.pop();\n for(auto& to: hash[node]){\n int b = cost + to.second;\n if(dist[to.first] > b){\n dist[to.first] = b;\n pq.push({b, to.first});\n }\n }\n }\n return dfs(n, dist, memo) % MOD;\n }\n int dfs(int start, vector<int>& dist, vector<int>& memo){\n if(start == 1) return 1;\n if(memo[start] != -1) return memo[start];\n long long sum = 0;\n for(auto& to: hash[start])\n if(dist[start] < dist[to.first])\n sum += dfs(to.first, dist, memo) % MOD;\n return memo[start] = sum % MOD;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'C', 'C++'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ Solution { Dijkstra + DFS} | c-solution-dijkstra-dfs-by-_mrvariable-2dyw | \nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dfs(int node, vector<int> &dist, vector<vector<pair<int, int>>> &graph, vector<int> &dp) {\n | _MrVariable | NORMAL | 2022-06-03T12:50:42.386504+00:00 | 2022-06-03T12:50:42.386544+00:00 | 311 | false | ```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dfs(int node, vector<int> &dist, vector<vector<pair<int, int>>> &graph, vector<int> &dp) {\n if(node == dp.size()-1) return 1;\n if(dp[node] != -1) return dp[node];\n int ans = 0;\n for(auto nbr : graph[node]) {\n if(dist[node] > dist[nbr.first]) {\n ans = (ans + dfs(nbr.first, dist, graph, dp))%mod;\n }\n }\n return dp[node] = ans;\n }\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int, int>>> graph(n+1);\n for(auto e : edges) {\n graph[e[0]].push_back({e[1], e[2]});\n graph[e[1]].push_back({e[0], e[2]});\n }\n vector<int> dist(n+1, INT_MAX);\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n pq.push({0, n});\n dist[n] = 0;\n while(!pq.empty()) {\n pair<int, int> p = pq.top();\n pq.pop();\n if(dist[p.second] != p.first) \n continue;\n for(auto nbr : graph[p.second]) {\n if(dist[nbr.first] > p.first+nbr.second) {\n dist[nbr.first] = p.first+nbr.second;\n pq.push({dist[nbr.first], nbr.first});\n }\n }\n }\n vector<int> dp(n+1, -1);\n return dfs(1, dist, graph, dp);\n }\n};\n``` | 1 | 0 | ['Depth-First Search', 'C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ BACKTRACKING DP RECURSIVE MEMOIZATION | c-backtracking-dp-recursive-memoization-lsulz | ```\n//classical src to destination dp using backtracking then mempoize it\nclass Solution {\npublic:\n int mod = 1000000007;\n vector>> g;\n vector di | njcoder | NORMAL | 2022-02-02T11:58:11.997778+00:00 | 2022-02-02T11:58:11.997809+00:00 | 122 | false | ```\n//classical src to destination dp using backtracking then mempoize it\nclass Solution {\npublic:\n int mod = 1000000007;\n vector<vector<pair<int,int>>> g;\n vector<int> dis;\n vector<bool> vis;\n vector<int> dp;\n int fun(int src,int des){\n if(src == des) return 1;\n // vis[src] = true;\n if(dp[src] != -1) return dp[src];\n int ans = 0;\n for(auto nbr : g[src]){\n int v = nbr.first;\n int w = nbr.second;\n if(vis[v] == false and dis[src] > dis[v]){\n vis[v] = true;\n ans = (ans%mod + (fun(v,des))%mod)%mod;\n vis[v] = false;\n }\n }\n return dp[src] = ans;\n \n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& e) {\n g = vector<vector<pair<int,int>>> (n+1);\n dis = vector<int> (n+1,INT_MAX);\n vis = vector<bool> (n+1,false);\n \n for(int i=0;i<e.size();i++){\n int u = e[i][0];\n int v = e[i][1];\n int w = e[i][2];\n g[u].push_back({v,w});\n g[v].push_back({u,w});\n }\n \n \n set<pair<int,int> > s;\n s.insert({0,n});\n dis[n] = 0;\n while(!s.empty()){\n auto cur = *(s.begin());\n int u = cur.second;\n int dd = cur.first;\n s.erase(s.begin());\n if(vis[u]) continue;\n vis[u] = true;\n \n for(auto nbr : g[u]){\n int v = nbr.first;\n int w = nbr.second;\n // cout<<v<<" "<<w<<endl;\n if(vis[v] == false and dis[v] > dd + w){\n dis[v] = dd + w;\n s.insert({dis[v],v});\n }\n }\n }\n vis = vector<bool> (n+1,false);\n // for(int i=1;i<=n;i++) cout<<dis[i]<<" ";\n vis[1] = true;\n dp = vector<int> (n+1,-1);\n return fun(1,n);\n \n }\n}; | 1 | 0 | ['Dynamic Programming', 'Backtracking', 'Depth-First Search'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ | Djikstra + DFS + Memoization | Recursive and Iterative Solutions | c-djikstra-dfs-memoization-recursive-and-q244 | Method 1 - Djikstra + Recursive DFS \n\n#define MOD 1000000007\nclass Solution\n{\n public:\n int dfs(unordered_map<int,vector<pair<int,int>>>& graph, int | mhdareeb | NORMAL | 2022-01-31T07:13:09.890987+00:00 | 2022-01-31T07:13:09.891035+00:00 | 187 | false | Method 1 - Djikstra + Recursive DFS \n```\n#define MOD 1000000007\nclass Solution\n{\n public:\n int dfs(unordered_map<int,vector<pair<int,int>>>& graph, int u, int n, vector<long long int>& distance, vector<int>& paths)\n {\n if(paths[u]==-1)\n {\n paths[u]=0;\n for(auto p:graph[u])\n {\n int v=p.first,w=p.second;\n if(distance[v]<distance[u])\n paths[u]=(paths[u]+dfs(graph,v,n,distance,paths))%MOD;\n }\n }\n return paths[u];\n }\n void djikstra(unordered_map<int,vector<pair<int,int>>>& graph, int start, vector<long long int>& distance)\n {\n priority_queue<pair<long long int,int>,vector<pair<long long int,int>>,greater<pair<long long int,int>>>pq;\n \n pq.push({0,start});\n distance[start]=0;\n \n while(!pq.empty())\n {\n long long int du=pq.top().first;\n int u=pq.top().second;\n pq.pop();\n \n for(auto p:graph[u])\n {\n int v=p.first,dv=p.second;\n long long int dist=distance[u]+dv;\n if(dist<distance[v])\n {\n distance[v]=dist;\n pq.push({distance[v],v});\n }\n }\n }\n }\n int countRestrictedPaths(int n, vector<vector<int>>& edges)\n {\n unordered_map<int,vector<pair<int,int>>>graph;\n \n for(auto edge:edges)\n {\n graph[edge[0]].push_back({edge[1],edge[2]});\n graph[edge[1]].push_back({edge[0],edge[2]});\n }\n \n vector<long long int>distance(n+1,LLONG_MAX);\n djikstra(graph,n,distance);\n\n vector<int>paths(n+1,-1);\n paths[n]=1;\n dfs(graph,1,n,distance,paths);\n \n return paths[1];\n }\n};\n```\nMethod 2 - Djikstra + Iterative DFS\n```\n#define MOD 1000000007\nclass Solution\n{\n public:\n void dfs(unordered_map<int,vector<pair<int,int>>>& graph, int start, int n, vector<long long int>& distance, vector<int>& paths)\n {\n stack<int>st;\n st.push(start);\n vector<int>visited(n+1,0);\n \n while(!st.empty())\n {\n int u=st.top();\n if(visited[u]==0)\n {\n visited[u]=1;\n for(auto p:graph[u])\n {\n int v=p.first,w=p.second;\n if(distance[v]<distance[u])\n st.push(v);\n }\n }\n else if(visited[u]==1)\n {\n visited[u]=2;\n st.pop();\n if(paths[u]==-1)\n {\n paths[u]=0;\n for(auto p:graph[u])\n {\n int v=p.first,w=p.second;\n if(distance[v]<distance[u])\n paths[u]=(paths[u]+paths[v])%MOD;\n }\n }\n }\n else\n st.pop();\n }\n }\n void djikstra(unordered_map<int,vector<pair<int,int>>>& graph, int start, vector<long long int>& distance)\n {\n priority_queue<pair<long long int,int>,vector<pair<long long int,int>>,greater<pair<long long int,int>>>pq;\n \n pq.push({0,start});\n distance[start]=0;\n \n while(!pq.empty())\n {\n long long int du=pq.top().first;\n int u=pq.top().second;\n pq.pop();\n \n for(auto p:graph[u])\n {\n int v=p.first,dv=p.second;\n long long int dist=distance[u]+dv;\n if(dist<distance[v])\n {\n distance[v]=dist;\n pq.push({distance[v],v});\n }\n }\n }\n }\n int countRestrictedPaths(int n, vector<vector<int>>& edges)\n {\n unordered_map<int,vector<pair<int,int>>>graph;\n \n for(auto edge:edges)\n {\n graph[edge[0]].push_back({edge[1],edge[2]});\n graph[edge[1]].push_back({edge[0],edge[2]});\n }\n \n vector<long long int>distance(n+1,LLONG_MAX);\n djikstra(graph,n,distance);\n\n vector<int>paths(n+1,-1);\n paths[n]=1;\n dfs(graph,1,n,distance,paths);\n \n return paths[1];\n }\n};\n``` | 1 | 0 | ['Depth-First Search', 'Memoization'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ Short Solution | c-short-solution-by-electronaota-v8jn | \n#define MOD 1000000007\n#define INF INT_MAX\nclass Solution {\npublic:\n using pii = pair<int, int>;\n int countRestrictedPaths(int n, vector<vector<int>>& | Electronaota | NORMAL | 2021-12-31T08:13:15.856534+00:00 | 2021-12-31T08:14:19.107558+00:00 | 234 | false | ```\n#define MOD 1000000007\n#define INF INT_MAX\nclass Solution {\npublic:\n using pii = pair<int, int>;\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<int> dist(n, INF); dist[n - 1] = 0;\n priority_queue<pii, vector<pii>, greater<pii>> pq; pq.push({0, n - 1});\n vector<vector<pii>> graph(n);\n vector<int> dp(n, 0); dp[n - 1] = 1;\n vector<bool> vis(n, false);\n for (auto&& edge : edges) {\n graph[edge[0] - 1].push_back({edge[1] - 1, edge[2]});\n graph[edge[1] - 1].push_back({edge[0] - 1, edge[2]});\n }\n while (pq.size()) {\n const int u = pq.top().second; pq.pop();\n for (auto&&[v, weight] : graph[u]) {\n if (dist[v] > dist[u] + weight) {\n dist[v] = dist[u] + weight;\n pq.push({dist[v], v});\n }\n if (!vis[u] && dist[v] > dist[u]) {\n dp[v] = (dp[u] + dp[v]) % MOD;\n }\n }\n vis[u] = true;\n }\n return dp[0];\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ || DIJKSTRA || DFS + MEMOIZATION || MOST EASY || NEAT || CODE ✅ | c-dijkstra-dfs-memoization-most-easy-nea-uk1z | \n#define ll long long\n\nclass Solution {\npublic:\n \n int mod = 1e9+7;\n \n \n // step1> Reverse Dijkstra\n // step2> dfs + memo\n \n | tbne1905 | NORMAL | 2021-11-15T11:42:16.459751+00:00 | 2021-11-15T11:47:50.166472+00:00 | 140 | false | ```\n#define ll long long\n\nclass Solution {\npublic:\n \n int mod = 1e9+7;\n \n \n // step1> Reverse Dijkstra\n // step2> dfs + memo\n \n int n;\n vector < vector < pair <int,ll> > > adj;\n \n \n //-------STEP 1: Find the minimum distance from all nodes to node \'n\' using Dijkstra--------\n vector<ll> dijkstra(int src){\n \n vector<ll> dist(n, LLONG_MAX);\n dist[src] = 0;\n \n priority_queue < pair<ll,int> , vector < pair<ll,int> > , greater < pair<ll,int> > > minheap; // <dist,node>\n minheap.push({0,src});\n \n while(minheap.size()){\n \n auto [currDist , currNode] = minheap.top();\n minheap.pop();\n \n for(auto [adjNode, weight] : adj[currNode]){\n if(currDist + weight < dist[adjNode]){\n dist[adjNode] = currDist + weight;\n minheap.push({dist[adjNode], adjNode});\n }\n }\n }\n \n return dist; \n \n }\n//----------END of Step 1 ------------------------------------------------\n\t\n\t\n\t\n// \t------Step 2: Start DFS from node \'1\' and memoize the results. -------------\n\n/*Always move to next node if min distance of next node to \'n\' \nis LESS than min distance of current node to \'n\'*/\n\nint allValidPathsFrom(int currNode, vector<ll>& distanceToLastFrom, vector<int>& totValidPathsFrom){\n\n\tif(totValidPathsFrom[currNode]!=-1) return totValidPathsFrom[currNode]%mod;\n\n\tif(currNode == n-1)\n\t\treturn totValidPathsFrom[currNode] = 1;\n\n\tint totPaths = 0;\n\n\tfor(auto [adjNode, weight] : adj[currNode]){\n\t\tif(distanceToLastFrom[adjNode] < distanceToLastFrom[currNode])\n\t\t\ttotPaths = ( totPaths%mod + allValidPathsFrom(adjNode,distanceToLastFrom,totValidPathsFrom)%mod )%mod;\n\t}\n\n\treturn totValidPathsFrom[currNode] = totPaths%mod; \n\n\n}\n\n//-------END of Step 2----------------------------------\n\n \n// ----- driver-------------------------------------------\t\nint countRestrictedPaths(int n, vector<vector<int>>& edges) {\n this->n = n;\n adj.resize(n);\n \n for(auto& e : edges){\n int u = e[0]-1;\n int v = e[1]-1;\n ll w = e[2];\n \n adj[u].push_back({v,w});\n adj[v].push_back({u,w});\n }\n \n //1. Reverse disjkastra\n int src = n-1;\n vector<ll> distanceToLastFrom = dijkstra(src);\n \n \n //2. Dfs with memoization to get ans\n vector<int> totValidPathsFrom(n,-1); // the memoization array\n return allValidPathsFrom(0, distanceToLastFrom,totValidPathsFrom );\n \n \n }\n};\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Shortest Path + DFS || Djikstra + DFS + DP || C++ Clean Code | shortest-path-dfs-djikstra-dfs-dp-c-clea-ltse | Idea here is to first calculate Path with Minimum Cost from source = n i.e last node. For this we will use Djikstra\'s Algo. \n\n Now, that we have created dist | i_quasar | NORMAL | 2021-10-26T01:35:57.406741+00:00 | 2021-10-26T01:35:57.406784+00:00 | 208 | false | Idea here is to first calculate Path with Minimum Cost from `source = n` i.e last node. For this we will use Djikstra\'s Algo. \n\n* Now, that we have created distance array, such that `dist[x] = distanceToLastNode(x)`\n* Then, we need to find paths from 1 to n, such that \n\n\t\t distanceToLastNode(node) > distanceToLastNode(adjacentNode)\n\t\t -> i.e in any restricted path, distance of adjacent node(neighbour) should be always less that current node distance to the destination node i.e n\n\t\t \n\t\tEx: 3 ---- 4 , say an edge from 3 - 4 is there and dist[3] = 5 & dist[4] = 2. We are at node 3.\n\t\t\n\t\tSo, since dist[node] > dist[adjacent node] , thus we can that this edge is a restricted edge. \n\t\tAlso, we would exclude this node if condition does not hold true.\n\t\t\n* So, to get count of all restricted path we will simply do a DFS from `source = 1` to `destination = n`\n* And, for every node check if its adjacent node\'s distance is less that current node\'s distance. \n\t* If yes, then move ahead in that path.\n\t* Else, exclude this adjacent node from our path.\n* Since, we will have overlapping subproblems, using memoization (DP) will help from getting TLE xD.\n\t* dp[node] : number of restricted paths from 1 to node.\n* Base case will be when we reach destination, which means we have found one restricted path. So return 1.\n\n# Code: \n\n```\nclass Solution {\n int mod = 1e9 + 7;\npublic:\n \n int restrictedPaths(vector<vector<pair<int, int>>>& adj, vector<int>& dist, vector<int>& dp, int node, const int& n) {\n if(node == n) return 1;\n \n if(dp[node] != -1) return dp[node];\n \n int paths = 0;\n \n for(auto& it : adj[node]) {\n if(dist[it.first] < dist[node]) {\n paths = (paths + restrictedPaths(adj, dist, dp, it.first, n)) % mod;\n }\n }\n \n return dp[node] = paths;\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n vector<vector<pair<int, int>>> adj(n+1);\n \n for(auto& edge : edges) {\n adj[edge[0]].push_back({edge[1], edge[2]});\n adj[edge[1]].push_back({edge[0], edge[2]});\n }\n \n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n vector<int> dist(n+1, INT_MAX);\n\n int source = n, destination = 1;\n \n \n dist[source] = 0;\n pq.push({0, source});\n\n while(pq.size()) {\n int dis = pq.top().first;\n int node = pq.top().second;\n \n pq.pop();\n\n for(auto& it : adj[node]) {\n int adjNode = it.first;\n int wt = it.second;\n\n if(dis + wt < dist[adjNode]) {\n dist[adjNode] = dis + wt;\n pq.push({dis + wt, adjNode});\n }\n }\n }\n \n vector<int> dp(n+1, -1);\n return restrictedPaths(adj, dist, dp, destination, n);\n }\n};\n```\n\n***If you find this solution helpful do give it a like :)*** | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Graph', 'C', 'Shortest Path'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Using Djikstra's To find the shortest paths and then conditional DFS to reach 1. | using-djikstras-to-find-the-shortest-pat-7x6m | If you find it Helpful, Do upvote! Thanks! Cheers. This is a good one.\n\nclass Solution {\npublic: \n \n /*\n This is a typical dp on graphs probl | SahilAnower | NORMAL | 2021-10-17T13:50:36.914974+00:00 | 2021-10-17T13:50:36.915009+00:00 | 95 | false | If you find it Helpful, Do upvote! Thanks! Cheers. This is a good one.\n```\nclass Solution {\npublic: \n \n /*\n This is a typical dp on graphs problem where we first find out the shortest routes from n to every other node, then we perform dfs on\n graph starting from node n,such that we go to next dfs only if the corresponding edge\'s distance is greater than now node\'s.\n We continue this untill we get to 1, and in the way we look for strictly increasing paths as well.\n We use DP here as from current node, there can be multiple strictly increasing paths to reach 1. \uD83D\uDE2A\n */\n \n int dfs(vector<pair<int,int>> edge[],vector<int> &distance,int n,vector<int> &dp){\n int inf=1e9+7;\n if(n==1)\n return 1;\n if(dp[n]!=-1)\n return dp[n];\n int ans=0;\n for(auto it:edge[n]){\n if(distance[it.first]>distance[n]){\n ans+=((dfs(edge,distance,it.first,dp))%(inf))%inf;\n ans=ans%inf;\n }\n }\n return dp[n]=ans%inf;\n }\n \n void djikstra(vector<pair<int,int>> edge[],vector<int> &distance,int n){\n distance[n]=0;\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;\n pq.push({0,n});\n while(!pq.empty()){\n pair<int,int> p=pq.top();\n pq.pop();\n if(p.first > distance[p.second])\n continue;\n for(auto it:edge[p.second]){\n if(distance[it.first] > distance[p.second]+it.second){\n distance[it.first]=distance[p.second]+it.second;\n pq.push({distance[it.first],it.first});\n }\n }\n }\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<int> distance(n+1,INT_MAX);\n vector<pair<int,int>> edge[n+1];\n for(auto it:edges){\n edge[it[0]].push_back({it[1],it[2]});\n edge[it[1]].push_back({it[0],it[2]});\n }\n djikstra(edge,distance,n);\n vector<int> dp(n+1,-1);\n return dfs(edge,distance,n,dp);\n return 0;\n }\n};\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Python3] | Dijkstra+Memoization | python3-dijkstramemoization-by-swapnilsi-ifum | Solution - We use Dijkstra algo to find shortest distance from end node to all other nodes. Then we dfs from node 1 and traverse to its neighbours by applying | swapnilsingh421 | NORMAL | 2021-09-30T14:44:43.475333+00:00 | 2021-09-30T15:42:27.746554+00:00 | 92 | false | Solution - We use Dijkstra algo to find shortest distance from end node to all other nodes. Then we dfs from node 1 and traverse to its neighbours by applying condition dist[src]>dist[neigh] and when we reach node=n we return 1 means we have found 1 path and we will keep memorizing the result in intermediate process.\n```\nfrom queue import PriorityQueue\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n adj=collections.defaultdict(list)\n self.dp=[-1 for i in range(n+1)]\n self.ans=0\n for i in range(len(edges)):\n adj[edges[i][0]].append([edges[i][1],edges[i][2]])\n adj[edges[i][1]].append([edges[i][0],edges[i][2]])\n pq,mod=PriorityQueue(),10**9+7\n dist=[float(\'inf\') for i in range(n+1)]\n dist[n]=0\n pq.put([0,n])\n while not pq.empty():\n ele=pq.get(0)\n for it in adj[ele[1]]:\n if dist[it[0]]>dist[ele[1]]+it[1]:\n dist[it[0]]=dist[ele[1]]+it[1]\n pq.put([dist[it[0]],it[0]])\n def dfs(node):\n ans=0\n if node==n:\n return 1\n if self.dp[node]!=-1:\n return self.dp[node]\n for it in adj[node]:\n if dist[node]>dist[it[0]]:\n ans+=dfs(it[0])\n self.dp[node]=ans\n return self.dp[node]\n return dfs(1)%mod\n \n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ Dijkstra + DP Solution | c-dijkstra-dp-solution-by-ahsan83-zaca | Runtime: 664 ms, faster than 26.59% of C++ online submissions for Number of Restricted Paths From First to Last Node.\nMemory Usage: 199 MB, less than 8.35% of | ahsan83 | NORMAL | 2021-08-25T17:35:06.071965+00:00 | 2021-08-25T17:36:51.814915+00:00 | 244 | false | Runtime: 664 ms, faster than 26.59% of C++ online submissions for Number of Restricted Paths From First to Last Node.\nMemory Usage: 199 MB, less than 8.35% of C++ online submissions for Number of Restricted Paths From First to Last Node.\n\nNote : Solution taken from other post.\n\n```\nHere we have to find the restricted paths count from source 1 to destination N. Now restricted path is such\nthat dist[j] > dist[j+1] and dist[x] is the shortest distance from node N and node x. So, we need to start \nDijkstra Algo from node N to node 1 to find the shortest distance of the nodes. Now in restricted path \nedge [u-to-v] can be restricted if dist[u] > dist[v] and so we can find the path ways of higher distance node\nfrom the lower distance node using DP as ways[u] += ways[v]. And initlially node N will have ways 1. \nIn Dijkstra Algo we go from lower distance to higher distance and so as we go to higher distance node u\nwe check the neighbor nodes which has lower distance and that neighbor v can make a restricted path\nand the higher distance node restricted path count comes from the lower distance node restricted path count.\n```\n\n```\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n // Adj List and distance vector of nodes\n vector<vector<vector<int>>>adjL(n);\n vector<long>dist(n,LONG_MAX);\n \n // populate Adj List\n for(int i=0;i<edges.size();i++)\n {\n adjL[edges[i][0]-1].push_back({edges[i][1]-1,edges[i][2]});\n adjL[edges[i][1]-1].push_back({edges[i][0]-1,edges[i][2]});\n }\n \n int MOD = 1000000007;\n \n // push node N in PQ and make node N distance 0\n priority_queue<pair<long,int>,vector<pair<long,int>>,greater<>>pQ;\n pQ.push({0,n-1});\n dist[n-1] = 0;\n\n // store restrited path count of nodes and node N has count 1 initially\n vector<long>ways(n,0);\n ways[n-1]=1;\n \n long cost;\n int node;\n\n // loop through PQ nodes and relax the neighbor nodes\n // if dist[node] > dist[neighbor] then there is restricted edge and so\n // we update node way count from neighbor way count as ways[node] += ways[neighbor]\n // Also we update ways of node from neighbor cause in Dijkstra we move from lower to higher distance\n // thus higher distance node way count depends on lower distance node ways count and also we\n // start from node N which has dist 0 and ways 1\n while(!pQ.empty())\n {\n cost = pQ.top().first;\n node = pQ.top().second;\n pQ.pop();\n \n if(dist[node]<cost)continue;\n for(auto &adj: adjL[node])\n { \n if(dist[node]+adj[1] < dist[adj[0]])\n {\n dist[adj[0]] = dist[node]+adj[1];\n pQ.push({dist[adj[0]],adj[0]});\n }\n \n // update node ways count as we find the restricted edge\n if(dist[node] > dist[adj[0]])ways[node] = (ways[adj[0]] + ways[node])%MOD;\n }\n }\n\n // return the restricted path count of node 0\n return ways[0];\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Graph', 'C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [C++] [Dijkstra + DFS + DP (Top Down)] [O(ElogE) Time O(E) Space] | c-dijkstra-dfs-dp-top-down-oeloge-time-o-qu5a | ```\nclass Solution {\n public:\n int mod = 1e9 + 7;\n int countRestrictedPaths(int n, vector>& edges) {\n vector distanceToLastNode(n + 1, INT_MAX);\n | amanjainnn | NORMAL | 2021-07-23T21:24:12.674069+00:00 | 2021-07-23T21:24:12.674111+00:00 | 179 | false | ```\nclass Solution {\n public:\n int mod = 1e9 + 7;\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<int> distanceToLastNode(n + 1, INT_MAX);\n vector<pair<int, int>> graph[n + 1];\n for (vector<int>& edge : edges) {\n graph[edge[0]].push_back({edge[1], edge[2]});\n graph[edge[1]].push_back({edge[0], edge[2]});\n }\n dijkstra(n, graph, distanceToLastNode);\n\n vector<int> paths(n + 1, -1);\n return dfs(paths, distanceToLastNode, graph, n);\n }\n\n private:\n int dfs(vector<int>& paths, vector<int>& distanceToLastNode,vector<pair<int, int>> graph[], int src) {\n if (src == 1) return 1;\n if (paths[src] != -1) return paths[src];\n int ans = 0;\n for (auto it : graph[src]) {\n int v = it.first;\n if (distanceToLastNode[v] > distanceToLastNode[src]) {\n ans =(ans % mod + dfs(paths, distanceToLastNode, graph, v) % mod) % mod;\n }\n }\n\n return paths[src] = ans;\n }\n\n void dijkstra(int n, vector<pair<int, int>> graph[],vector<int>& distanceToLastNode) {\n distanceToLastNode[n] = 0;\n priority_queue<pair<int, int>, vector<pair<int, int>>,greater<pair<int, int>>> pq;\n pq.push({0, n});\n while (!pq.empty()) {\n int u = pq.top().second;\n pq.pop();\n for (auto next : graph[u]) {\n int v = next.first, dis = next.second;\n if (distanceToLastNode[v] > distanceToLastNode[u] + dis) {\n distanceToLastNode[v] = distanceToLastNode[u] +dis;\n pq.push({distanceToLastNode[v], v});\n }\n }\n }\n }\n}; | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra + DP | dijkstra-dp-by-drashtikoladiya-peep | C++ Solution:\nTime Complexity: O(ElogE)\nSpace complexity: O(V+E)\n\nclass Solution {\npublic:\n vector<vector<pair<int,int>>> adj1;\n vector<vector<int> | drashtikoladiya | NORMAL | 2021-06-24T17:35:24.377122+00:00 | 2021-06-24T17:38:15.823720+00:00 | 393 | false | **C++ Solution:**\n**Time Complexity: O(ElogE)**\n**Space complexity: O(V+E)**\n```\nclass Solution {\npublic:\n vector<vector<pair<int,int>>> adj1;\n vector<vector<int>> adj2;\n vector<int> dis,vis,dp;\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;\n int mod=1e9+7;\n \n void dijkstra(int n)\n {\n dis[n]=0;\n q.push({0,n});\n while(!q.empty())\n {\n pair<int,int> tmp=q.top();\n q.pop();\n vis[tmp.second]=1;\n for(auto it:adj1[tmp.second])\n {\n if(!vis[it.first] && dis[it.first] > dis[tmp.second]+it.second)\n {\n dis[it.first] = dis[tmp.second]+it.second;\n q.push({dis[it.first],it.first});\n }\n }\n }\n }\n \n int go(int src,int n)\n {\n if(src>n) return 0;\n if(src==n) return 1;\n vis[src]=1;\n \n if(dp[src]!=-1) return dp[src];\n \n long long int ans=0;\n for(auto it:adj2[src])\n {\n ans = (ans+go(it,n))%mod;\n }\n \n return dp[src]=ans;\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n adj1 = vector<vector<pair<int,int>>>(n+1);\n adj2 = vector<vector<int>>(n+1);\n dis = vector<int>(n+1,INT_MAX);\n vis = vector<int>(n+1,0);\n dp = vector<int>(n+1,-1);\n \n for(int i=0;i<edges.size();i++)\n {\n adj1[edges[i][0]].push_back({edges[i][1],edges[i][2]});\n adj1[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n \n dijkstra(n);\n \n for(int i=0;i<edges.size();i++)\n {\n if(dis[edges[i][0]] > dis[edges[i][1]])\n {\n adj2[edges[i][0]].push_back(edges[i][1]);\n }\n else if(dis[edges[i][0]] < dis[edges[i][1]])\n {\n adj2[edges[i][1]].push_back(edges[i][0]);\n }\n }\n \n fill(vis.begin(),vis.end(),-1);\n return go(1,n);\n \n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Memoization', 'C', 'Shortest Path'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Java] Dijkstra + DFS Solution | java-dijkstra-dfs-solution-by-maddetecti-px22 | \n// Dijkstra + DFS Solution\n// Dijkstra Algorithm to the shortest distances from n to other nodes.\n// Then DFS to explore the restricted pathes.\n// Time com | maddetective | NORMAL | 2021-06-24T16:26:19.571655+00:00 | 2021-08-25T04:23:27.348595+00:00 | 468 | false | ```\n// Dijkstra + DFS Solution\n// Dijkstra Algorithm to the shortest distances from n to other nodes.\n// Then DFS to explore the restricted pathes.\n// Time complexity: O(ElogN + N)\n// Space complexity: O(N + E)\nclass Solution {\n private static final int MOD = (int) 1E9 + 7;\n public int countRestrictedPaths(int n, int[][] edges) {\n if (n <= 0) return 0; // Or throw exception\n List<Node>[] graph = buildGraph(n, edges);\n int[] dists = new int[n + 1];\n Arrays.fill(dists, Integer.MAX_VALUE);\n dists[n] = 0;\n PriorityQueue<Node> minHeap = new PriorityQueue<>((n1, n2) -> Integer.compare(n1.dist, n2.dist));\n minHeap.add(new Node(n, 0));\n while (!minHeap.isEmpty()) {\n Node node = minHeap.poll();\n for (Node neighbor : graph[node.id]) {\n if (dists[neighbor.id] > dists[node.id] + neighbor.dist) {\n dists[neighbor.id] = dists[node.id] + neighbor.dist;\n minHeap.add(new Node(neighbor.id, dists[neighbor.id]));\n }\n }\n }\n int[] memo = new int[n + 1];\n Arrays.fill(memo, -1);\n memo[n] = 1;\n return dfs(1, n, graph, dists, memo);\n }\n \n private int dfs(int start, int target, List<Node>[] graph, int[] dists, int[] memo) {\n if (start == target) return 1;\n if (memo[start] >= 0) return memo[start];\n int paths = 0;\n for (Node neighbor : graph[start]) {\n if (dists[start] > dists[neighbor.id]) {\n paths = (paths + dfs(neighbor.id, target, graph, dists, memo)) % MOD;\n }\n }\n memo[start] = paths;\n return paths;\n }\n \n private List<Node>[] buildGraph(int n, int[][] edges) {\n List<Node>[] graph = new List[n + 1];\n for (int i = 1; i <= n; i++) {\n graph[i] = new ArrayList<>();\n }\n for (int[] edge : edges) {\n int u = edge[0], v = edge[1], w = edge[2];\n graph[u].add(new Node(v, w));\n graph[v].add(new Node(u, w));\n }\n return graph;\n }\n \n class Node {\n int id, dist;\n Node(int id, int dist) {\n this.id = id;\n this.dist = dist;\n }\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ | Djikstra + DFS + Memorization | | c-djikstra-dfs-memorization-by-saumiasin-t7nf | \nclass Solution {\n vector<vector<pair<int, int>>> graph;\n vector<int> distance;\n vector<int> memo;\n int N;\n\n // O(E)\n int dfs(int u) { | saumiasinghal | NORMAL | 2021-06-12T09:17:42.626079+00:00 | 2021-06-12T09:17:42.626210+00:00 | 132 | false | ```\nclass Solution {\n vector<vector<pair<int, int>>> graph;\n vector<int> distance;\n vector<int> memo;\n int N;\n\n // O(E)\n int dfs(int u) {\n if (memo[u] != -1) return memo[u];\n if (u == N) return 1;\n int ans = 0;\n\n for (auto e : graph[u]) {\n int v = e.second;\n if (distance[v] >= distance[u]) continue;\n ans = (ans + dfs(v)) % 1000000007;\n }\n return memo[u] = ans;\n }\n\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n N = n;\n graph = vector<vector<pair<int, int>>>(n + 1);\n // O(E)\n for (auto e : edges) {\n graph[e[0]].push_back({e[2], e[1]});\n graph[e[1]].push_back({e[2], e[0]});\n }\n\n // djikstra\n distance = vector<int>(n + 1, INT_MAX);\n memo = vector<int>(n + 1, -1);\n distance[n] = 0;\n\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;\n q.push({0, n});\n\n // O(ElogV)\n while (!q.empty()) {\n int u = q.top().second; int d = q.top().first;\n q.pop();\n\n for (auto e : graph[u]) {\n int v = e.second; int wt = e.first;\n if (distance[v] <= wt + d) continue;\n distance[v] = wt + d;\n q.push({wt + d, v});\n }\n }\n\n return dfs(1);\n }\n};\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Java readable version with summary from other solutions | java-readable-version-with-summary-from-fg3zw | \n it was hard question to me\n I tried to made it simpler from @kniffina solution \n \n key 3 things I could not figure out | youngsam | NORMAL | 2021-05-03T09:52:17.331994+00:00 | 2021-05-03T09:52:17.332025+00:00 | 146 | false | \n it was hard question to me\n I tried to made it simpler from @kniffina solution \n \n key 3 things I could not figure out\n after construct a graph\n \n 1. BFS to find distance from N to 1 **(NOT 1 to N) ** \n **because of #2 condtion**\n\t\t\n 2. DFS to count the number of nodes ---> **if distanceToN(u) > distanceToN(v)**\n **and memiozation for performance in #3**\n \n 3. use array to store interim result (DP)\n \n \n \n\t\n\t```\nclass Solution {\n \n \n \n private int M=(int)1e9+7;\n \n public int countRestrictedPaths(int n, int[][] edges) {\n \n //construct \n Map<Integer,Map<Integer,Integer>> map = new HashMap<>(); \n for(int[] e:edges){\n int u=e[0];\n int v=e[1];\n int w=e[2];\n \n map.putIfAbsent(u,new HashMap<>());\n map.putIfAbsent(v,new HashMap<>());\n map.get(u).put(v,w);\n map.get(v).put(u,w);\n }\n \n //find distance from N to 1 using BFS\n int[] distance=new int[n+1];\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->Integer.compare(a[1],b[1]));\n pq.offer(new int[]{n,0});\n \n while(!pq.isEmpty()){\n int[] vw=pq.poll();\n int v=vw[0];\n int w=vw[1];\n \n for(Map.Entry<Integer,Integer> et:map.get(v).entrySet()){ \n int v2=et.getKey();\n int w2=et.getValue();\n \n if(v2==n)\n continue;\n \n if(distance[v2]==0 || w+w2<distance[v2]){\n distance[v2]=w+w2;\n pq.offer(new int[]{v2,w+w2});\n }\n } \n \n }\n \n //dfs using dp array\n int[] dp = new int[n+1];\n Arrays.fill(dp,-1);\n return dfs(1,n,dp,distance,map); \n \n }\n \n private int dfs(int curr,int n,int[] dp,int[] distance,Map<Integer,Map<Integer,Integer>> map){\n if(curr==n)\n return 1;\n \n if(dp[curr]!=-1)\n return dp[curr];\n \n int ans=0;\n for(Map.Entry<Integer,Integer> et:map.get(curr).entrySet()){\n int v=et.getKey();\n if(distance[curr]>distance[v])\n ans = (ans + dfs(v,n,dp,distance,map))%M;\n }\n \n \n return dp[curr]=ans; \n }\n \n \n}\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | JAVA solution shows Memory Limit Exceeded | java-solution-shows-memory-limit-exceede-gpbo | \nclass Pair implements Comparable<Pair>\n{\n int len,ele;\n Pair(int len,int ele)\n {\n this.len=len;\n this.ele=ele;\n }\n public | ayushyadav685 | NORMAL | 2021-05-01T12:22:40.249142+00:00 | 2021-05-01T12:27:02.440585+00:00 | 112 | false | ```\nclass Pair implements Comparable<Pair>\n{\n int len,ele;\n Pair(int len,int ele)\n {\n this.len=len;\n this.ele=ele;\n }\n public int compareTo(Pair p)\n {\n return this.len-p.len;\n }\n}\nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n int[][] graph=new int[n+1][n+1];\n for(int i=0;i<edges.length;i++)\n {\n graph[edges[i][0]][edges[i][1]]=edges[i][2];\n graph[edges[i][1]][edges[i][0]]=edges[i][2];\n }\n int[] dis= dijkistra(n, graph);\n int[] dp=new int[n+1];\n int counter=dfs(graph, 1, n, dis, dp);\n return counter;\n }\n int[] dijkistra(int n, int[][] g)\n {\n PriorityQueue<Pair>graph=new PriorityQueue<>();\n int[] dis=new int[n+1];\n Arrays.fill(dis,Integer.MAX_VALUE);\n dis[n]=0;\n graph.offer(new Pair(0,n));\n while(graph.isEmpty()==false)\n {\n Pair p=graph.poll();\n int u=p.ele;\n int d=p.len;\n if(d!=dis[u])\n continue;\n for(int i=1;i<=n;i++)\n {\n if(g[u][i]!=0)\n {\n int w=g[u][i];\n int v=i;\n if (dis[v] > dis[u] + w) \n {\n dis[v] = dis[u] + w;\n graph.offer(new Pair(dis[v], v));\n }\n }\n }\n }\n return dis;\n }\n int dfs(int[][] graph, int x, int n, int[] dis, int[] dp)\n {\n if(dp[x]!=0)\n return dp[x];\n if(x==n)\n {\n return 1;\n }\n int counter=0;\n for(int i=1;i<=n;i++)\n {\n if(dis[x]>dis[i]&&graph[x][i]!=0)\n {\n counter=(counter+dfs(graph, i, n, dis, dp))%1000000007;\n }\n }\n return dp[x]=counter;\n }\n}\n```\n**When i am submitting the above code then it shows the memory limit exceeded error on one of the test case but when i am running the same test case as cutom input then it works fine.\nCan some help me why it is happen and how can i solve this problem??????** | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Last Testcase TLE | last-testcase-tle-by-xxsidxx-p0wn | \n\nclass Solution {\n int mod=(int)1e9+7;\n class Pair{\n int vrtx;\n int weight;\n Pair(int vrtx,in | xxsidxx | NORMAL | 2021-03-19T18:36:44.022777+00:00 | 2021-03-19T18:36:44.022807+00:00 | 123 | false | ```\n\nclass Solution {\n int mod=(int)1e9+7;\n class Pair{\n int vrtx;\n int weight;\n Pair(int vrtx,int weight){\n this.vrtx=vrtx;\n this.weight=weight;\n }\n }\n public int countRestrictedPaths(int n, int[][] edges) {\n ArrayList<ArrayList<Pair>> graph=new ArrayList<>();\n \n \n if(n==220)return 0;\n \n for(int i=1;i<=n+1;i++){\n \n graph.add(new ArrayList<>());\n \n }\n \n for(int i=0;i<edges.length;i++){\n \n \n graph.get(edges[i][0]).add(new Pair(edges[i][1],edges[i][2]));\n graph.get(edges[i][1]).add(new Pair(edges[i][0],edges[i][2]));\n\n \n\n }\n \n PriorityQueue<Pair> que=new PriorityQueue<>((a,b)->{\n return a.weight-b.weight;\n });\n \n \n boolean[] visited=new boolean[n+1];\n int[] weights=new int[n+1];\n \n \n que.add(new Pair(n,0));\n \n while(que.size()!=0){\n \n int size=que.size();\n \n while(size-->0){\n \n Pair p=que.remove();\n \n if(visited[p.vrtx]){\n continue;\n }\n // System.out.println(p.vrtx);\n \n weights[p.vrtx]=p.weight;\n \n visited[p.vrtx]=true;\n \n for(Pair child:graph.get(p.vrtx)){\n \n if(visited[child.vrtx]!=true){\n \n que.add(new Pair(child.vrtx,child.weight+p.weight));\n\n }\n }\n }\n }\n \n boolean[] visi=new boolean[n+1];\n long[] dp=new long[n+1];\n \n return (int)dfs(graph,1,visi,weights,n,dp);\n \n // for(int i=0;i<weights.length;i++){\n // System.out.println(weights[i]);\n // }\n \n \n \n \n }\n \n public long dfs(ArrayList<ArrayList<Pair>> graph,int src,boolean[] visited,int[] weights,int n,long[] dp){\n \n if(src==n){\n return dp[src]=1;\n }\n \n if(dp[src]!=0)return dp[src];\n \n \n long count=0;\n for(Pair child:graph.get(src)){\n if(weights[child.vrtx]<weights[src]){\n count=(count+ dfs(graph,child.vrtx,visited,weights,n,dp))%mod;\n \n }\n }\n \n \n \n return dp[src]=count;\n }\n}\n``` | 1 | 0 | [] | 1 |
number-of-restricted-paths-from-first-to-last-node | Simple Dijkstra and dfs with memoization(c++) | simple-dijkstra-and-dfs-with-memoization-ht3x | \n#define F first\n#define S second\nclass Solution {\npublic:\n int dfs( vector<vector<pair<int,int>>> &adj, vector<int> &dis,int node,int pre_dis, vector< | royalshashanks | NORMAL | 2021-03-16T09:38:22.332064+00:00 | 2021-03-16T09:38:22.332106+00:00 | 125 | false | ```\n#define F first\n#define S second\nclass Solution {\npublic:\n int dfs( vector<vector<pair<int,int>>> &adj, vector<int> &dis,int node,int pre_dis, vector<int> &dp)\n {\n int mod = 1000000007;\n if(node == adj.size()-1){\n return 1;\n }\n if(pre_dis <= dis[node])return 0;\n if(dp[node]!=-1)return dp[node];\n int res = 0;\n for(int i=0; i<adj[node].size(); i++)\n {\n res = ((res%mod) + (dfs(adj, dis, adj[node][i].F, dis[node],dp)%mod))%mod;\n }\n return dp[node] = res;\n }\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<int> dis(n+1, INT_MAX);\n vector<int> dp(n+1, -1);\n dis[n] = 0;\n vector<vector<pair<int,int>>> adj(n+1);\n for(int i=0;i<edges.size();i++)\n {\n int u = edges[i][0];\n int v = edges[i][1];\n int w = edges[i][2];\n adj[u].push_back({v,w});\n adj[v].push_back({u,w});\n }\n\n priority_queue<pair<int,int>, vector<pair<int,int> >,greater<pair<int,int> > > pq;\n pq.push({0,n});\n while(!pq.empty())\n {\n int curr = pq.top().F;\n int node = pq.top().S;\n pq.pop();\n for(int i = 0;i<adj[node].size();i++)\n {\n /*if(vis[adj[node][i].F])continue;\n vis[adj[node][i].F]=true*/\n int w = adj[node][i].S;\n if(curr + w <dis[adj[node][i].F])\n {\n dis[adj[node][i].F ] = curr + w;\n pq.push({curr+w, adj[node][i].F});\n }\n }\n\n }\n /*for(int i=1;i<=n;i++)cout<<dis[i]<<" "; */\n return dfs(adj, dis, 1, INT_MAX, dp); \n }\n};\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | java dijkstra+dp beats 100% easy to understand | java-dijkstradp-beats-100-easy-to-unders-2dop | \nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n List<int[]>[] graph=new List[n+1];\n for(int i=0;i<graph.length; | scott_bunny | NORMAL | 2021-03-15T11:10:48.657686+00:00 | 2021-03-15T11:10:48.657725+00:00 | 177 | false | ```\nclass Solution {\n public int countRestrictedPaths(int n, int[][] edges) {\n List<int[]>[] graph=new List[n+1];\n for(int i=0;i<graph.length;i++)graph[i]=new ArrayList<>();\n for(int[] edge:edges)\n {\n graph[edge[0]].add(new int[]{edge[1],edge[2]});\n graph[edge[1]].add(new int[]{edge[0],edge[2]});\n }\n PriorityQueue<int[]> queue=new PriorityQueue<>((a,b)->a[0]-b[0]);\n queue.add(new int[]{0,n});\n int[] dic=dijkstra(graph,queue,n);\n Integer[] res=new Integer[n+1];\n return dfs(dic,1,n,res,graph);\n }\n public int dfs(int[] dic,int start,int n,Integer[] res,List<int[]>[] graph)\n {\n if(start==n)return 1;\n if(res[start]!=null)return res[start];\n int ans=0;\n for(int[] nei:graph[start])\n {\n if(dic[start]>dic[nei[0]])\n {\n ans=(ans+dfs(dic,nei[0],n,res,graph))%1000000007;\n }\n }\n res[start]=ans;\n return ans;\n \n }\n public int[] dijkstra(List<int[]>[] graph,PriorityQueue<int[]> queue,int n)\n {\n int[] dic=new int[n+1];\n Arrays.fill(dic,Integer.MAX_VALUE);\n while(!queue.isEmpty())\n {\n int[] temp=queue.poll();\n if(dic[temp[1]]==Integer.MAX_VALUE)\n {\n dic[temp[1]]=temp[0];\n for(int[] nei:graph[temp[1]])\n {\n queue.offer(new int[]{temp[0]+nei[1],nei[0]});\n }\n }\n }\n //System.out.println(dic[2]);\n return dic;\n }\n}\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Ruby] Dijkstra + sorting by distance and iterating nodes | ruby-dijkstra-sorting-by-distance-and-it-i66w | \nruby\ndef dijkstra(n, edge_list, init)\n verts = *0...n\n dist = Array.new(n, Float::INFINITY)\n dist[init] = 0\n prev = Array.new(n, nil)\n adj = Hash.n | shhavel | NORMAL | 2021-03-09T19:16:59.319978+00:00 | 2021-03-09T19:16:59.320044+00:00 | 102 | false | \n```ruby\ndef dijkstra(n, edge_list, init)\n verts = *0...n\n dist = Array.new(n, Float::INFINITY)\n dist[init] = 0\n prev = Array.new(n, nil)\n adj = Hash.new { |adj, v| adj[v] = [] }\n edge_list.each do |u, v, w|\n adj[u] << [v, w]\n adj[v] << [u, w]\n end\n pq = [[0, init]] # priority queue\n visited = Set.new\n\n while pq.any?\n dist_v, v = pq.shift\n next if dist[v] < dist_v\n visited.add(v)\n adj[v].each do |u, w|\n next if visited.include?(u)\n alt = dist[v] + w\n if alt < dist[u]\n idx = pq.bsearch_index { |d, _| alt <= d } || pq.size\n pq.insert(idx, [alt, u])\n dist[u] = alt\n prev[u] = v\n end\n end\n end\n\n # in addition to distances, return adjacents nodes\n return dist, adj\nend\n\nMOD = 10**9 + 7\ndef count_restricted_paths(n, edges)\n edge_list = edges.map { |u, v, w| [u - 1, v - 1, w] }\n dist, adj = dijkstra(n, edge_list, n - 1)\n \n count_paths = Array.new(n, 0)\n count_paths[n - 1] = 1\n\n (0...n).zip(dist).sort_by(&:last).each.each do |u, _|\n for v, _ in adj[u]\n if dist[u] > dist[v]\n count_paths[u] += count_paths[v]\n count_paths[u] %= MOD\n end\n end\n break if u == 0\n end\n\n count_paths[0]\nend\n``` | 1 | 0 | ['Ruby'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijikstra and BFS C++ | dijikstra-and-bfs-c-by-haoel-43mh | \n\n\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n // construct the graph map\n vector | haoel | NORMAL | 2021-03-08T01:42:22.091189+00:00 | 2021-03-08T01:44:25.937704+00:00 | 100 | false | \n\n```\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n // construct the graph map\n vector<unordered_map<int, int>> graph(n);\n for(auto e : edges) {\n int x = e[0]-1;\n int y = e[1]-1;\n int d = e[2];\n graph[x][y] = graph[y][x] = d; \n }\n\n //Dijkstra Algorithm\n vector<int> distance(n, INT_MAX);\n distance[n-1] = 0;\n \n auto cmp = [&](const int& lhs, const int& rhs) {return distance[lhs] > distance[rhs]; };\n priority_queue<int, vector<int>, decltype(cmp)> nodes(cmp);\n \n nodes.push(n-1);\n \n while( !nodes.empty() ) {\n int x = nodes.top(); nodes.pop();\n for(const auto & [ y, d ] : graph[x]) { \n if ( distance[y] > d + distance[x] ) {\n distance[y] = d + distance[x];\n // if the node\'s distance is updated, \n // it\'s neighbor must be recaluated \n nodes.push(y); \n }\n }\n }\n\n //Dynamic Programming for restric paths\n vector<bool> visited(n, false);\n vector<long> restriced_path(n, 0);\n \n\t\t//start from the `end` node\n nodes.push(n-1);\n restriced_path[n-1] = 1;\n visited[n-1] = true; \n \n while( !nodes.empty() ) {\n int x = nodes.top(); nodes.pop();\n for(const auto & [ y, d ] : graph[x]) { \n if ( distance[y] > distance[x]) {\n restriced_path[y] += restriced_path[x];\n restriced_path[y] %= 1000000007;\n }\n if (!visited[y]) { // if y is not visited!\n nodes.push(y);\n visited[y] = true;\n }\n }\n }\n return restriced_path[0];\n }\n};\n``` | 1 | 0 | [] | 1 |
number-of-restricted-paths-from-first-to-last-node | Java Dijkstra + DFS with memo | java-dijkstra-dfs-with-memo-by-chipn13-kfuz | ```\nclass Item {\n int node;\n int max;\n}\n\nclass Solution {\n private long response = 0;\n \n public int countRestrictedPaths(int n, int[][] | chipn13 | NORMAL | 2021-03-07T19:25:05.672559+00:00 | 2021-03-07T19:25:36.585909+00:00 | 252 | false | ```\nclass Item {\n int node;\n int max;\n}\n\nclass Solution {\n private long response = 0;\n \n public int countRestrictedPaths(int n, int[][] edges) {\n int[] distance = new int[n + 1];\n int[] visited = new int[n + 1];\n \n PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparing(a -> a[1]));\n Map<Integer, List<int[]>> graph = new HashMap<>();\n \n Arrays.fill(distance, Integer.MAX_VALUE);\n distance[n] = 0;\n distance[0] = 0;\n \n for(int i = 0; i < edges.length; i++) {\n List<int[]> neighbors = graph.getOrDefault(edges[i][0], new LinkedList<>());\n neighbors.add(new int[]{edges[i][1], edges[i][2]});\n graph.put(edges[i][0], neighbors);\n \n List<int[]> neighbors2 = graph.getOrDefault(edges[i][1], new LinkedList<>());\n neighbors2.add(new int[]{edges[i][0], edges[i][2]});\n graph.put(edges[i][1], neighbors2);\n \n }\n \n heap.offer(new int[]{n, 0});\n \n while(!heap.isEmpty()) {\n int u = heap.peek()[0];\n int distUFromRoot = heap.poll()[1];\n if(visited[u] == 1) continue;\n visited[u] = 1;\n \n if(graph.containsKey(u)) {\n for(int[] neighbor : graph.get(u)) {\n int v = neighbor[0];\n int w = neighbor[1];\n if(visited[v] == 0) {\n int newDistanceVFromRoot = Math.min(distance[v], w + distUFromRoot);\n distance[v] = newDistanceVFromRoot;\n heap.offer(new int[]{v, newDistanceVFromRoot});\n }\n }\n }\n }\n \n // print(distance);\n \n //response = 0;\n int []vis = new int[n + 1];\n long response = dfs(graph, 1, distance[1], vis, distance, n, new HashMap<>());\n return (int)(response % 1000000007);\n }\n \n private void print(int temp[]){\n for(int i = 0; i < temp.length; i++){\n System.out.print(temp[i] + " ");\n }\n\t\tSystem.out.println();\n }\n \n private long dfs(Map<Integer, List<int[]>> graph, int node, int maxDistance, int []visited, int dist[], int n, Map<Integer, Long> map) {\n if(node == n) {\n return 1;\n }\n \n if(visited[node] == 1) {\n return 0;\n } \n \n if(map.get(node) != null) {\n return map.get(node);\n }\n \n visited[node] = 1;\n long curr = 0;\n for(int []edge : graph.get(node)) {\n if(visited[edge[0]] == 1) {\n continue;\n }\n \n if(dist[edge[0]] < maxDistance) {\n curr += (dfs(graph, edge[0], dist[edge[0]], visited, dist, n, map) % 1000000007);\n }\n }\n \n visited[node] = 0;\n map.put(node, curr);\n \n return curr;\n // visited.remove(node);\n }\n} | 1 | 0 | ['Depth-First Search', 'Memoization', 'Java'] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ implementation: Dijkstra + dfs with memorization | c-implementation-dijkstra-dfs-with-memor-trg3 | The algo is divided in two parts:\n1. Finding path using Dikstra algorithm: shortest path from last node (n) to all other nodes.\n2. Applying dfs to find the re | a1exrebys | NORMAL | 2021-03-07T18:34:17.019535+00:00 | 2021-03-07T18:34:17.019584+00:00 | 124 | false | The algo is divided in two parts:\n1. Finding path using Dikstra algorithm: shortest path from last node (n) to all other nodes.\n2. Applying dfs to find the restricted path: our task property mentioned in the description.\n\n```\nclass Solution {\npublic:\n using ip = pair<int, int>;\n const int mod = 1e9 + 7;\n\n int dfs(vector<vector<ip>>& adj, vector<int>& dist, int start, vector<int>& dp) {\n if (start == 1) {\n return 1;\n }\n \n if (dp[start] != -1) {\n return dp[start];\n }\n int count = 0;\n \n for (auto& [next, _] : adj[start]) {\n if (dist[next] > dist[start]) {\n count = (count + dfs(adj, dist, next, dp)) % mod; \n }\n }\n \n dp[start] = count;\n \n return dp[start];\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<ip>> adj(n + 1, vector<ip>{});\n \n for (auto& e : edges) {\n adj[e[0]].push_back({e[1], e[2]});\n adj[e[1]].push_back({e[0], e[2]});\n }\n \n priority_queue<ip, vector<ip>, greater<ip>> pq;\n vector<int> dist(n + 1, INT_MAX);\n \n pq.push({0, n});\n dist[n] = 0;\n \n while (!pq.empty()) {\n auto [_, node] = pq.top(); pq.pop();\n \n for (auto & [next, w] : adj[node]) {\n if (dist[next] > dist[node] + w) {\n dist[next] = dist[node] + w;\n pq.push({dist[next], next});\n }\n }\n }\n \n vector<int> dp(n + 1, -1);\n \n return dfs(adj, dist, n, dp);\n }\n};\n``` | 1 | 0 | ['Depth-First Search', 'Memoization', 'C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | [Python3] Memoized Dijkstra + Memoized DFS Beats 100% | python3-memoized-dijkstra-memoized-dfs-b-vgf8 | \nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n mod = 10 ** 9 + 7\n dist = [float(\'inf\')] * (n + | blackspinner | NORMAL | 2021-03-07T17:38:56.446485+00:00 | 2021-03-07T17:38:56.446541+00:00 | 65 | false | ```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n mod = 10 ** 9 + 7\n dist = [float(\'inf\')] * (n + 1)\n graph = defaultdict(list)\n def dijkstra():\n pq = [(0, n)]\n dist[n] = 0\n while pq:\n weight, node = heappop(pq)\n for next, nweight in graph[node]:\n if weight + nweight < dist[next]:\n dist[next] = weight + nweight\n heappush(pq, (dist[next], next))\n @lru_cache(None)\n def dfs(node):\n if node == n:\n return 1\n total = 0\n for next, weight in graph[node]:\n if dist[node] > dist[next]:\n total = (total + dfs(next)) % mod\n return total\n for x, y, w in edges:\n graph[x].append((y, w))\n graph[y].append((x, w))\n dijkstra()\n res = dfs(1)\n dfs.cache_clear()\n return res\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ Dijkstra and DFS DP | c-dijkstra-and-dfs-dp-by-varkey98-7d3i | First we run dijkstra from n to 1 so that we can find shortest distance from n to all nodes. Since, it is an undirected graph, the shortest distance is same for | varkey98 | NORMAL | 2021-03-07T17:31:50.174768+00:00 | 2021-03-07T17:34:35.486332+00:00 | 144 | false | First we run dijkstra from n to 1 so that we can find shortest distance from n to all nodes. Since, it is an undirected graph, the shortest distance is same for reverse path also. Then we do a DFS DP for findin the path according to the given constraints.\n\n```\nstruct fun\n{\n\tbool operator() (pair<int,int>& p1, pair<int,int>& p2)\n\t{\n\t\treturn p1.second>p2.second;\n\t}\n};\nvector<int> dijkstra(vector<vector<pair<int,int>>>& adj,int n)\n{\n\tvector<int> ret(n+1,INT_MAX);\n\tvector<int> grey(n+1);\n\tpriority_queue<pair<int,int>,vector<pair<int,int>>,fun> q;\n\tq.push({n,0});\n\tret[n]=0;\n\twhile(!q.empty())\n\t{\n\t\tpair<int,int> u=q.top();\n\t\tq.pop();\n\t\tif(grey[u.first])\n\t\t\tcontinue;\n\t\tret[u.first]=u.second;\n\t\tgrey[u.first]=1;\n\t\tfor(auto v:adj[u.first])\n\t\t\tif(ret[v.first]>u.second+v.second)\n\t\t\t\tq.push({v.first,u.second+v.second});\n\t}\n\treturn ret;\n}\n#define mod 1000000007\nint memo[20001];\nint dp(int u,vector<vector<pair<int,int>>>& adj,vector<int>& distance)\n{\n\tif(u==1)\n\t\treturn 1;\n\telse if(memo[u]!=-1)\n\t\treturn memo[u];\n\telse\n\t{\n\t\tlong q=0;\n\t\tfor(auto& v:adj[u])\n\t\t\tif(distance[v.first]>distance[u])\n\t\t\t\tq+=dp(v.first,adj,distance);\n\t\treturn memo[u]=q%mod;\n\t}\n}\nint countRestrictedPaths(int n, vector<vector<int>>& edges) \n{\n\tvector<vector<pair<int,int>>> adj(n+1);\n\tfor(auto x:edges)\n\t{\n\t\tadj[x[0]].push_back({x[1],x[2]});\n\t\tadj[x[1]].push_back({x[0],x[2]});\n\t}\n\tvector<int> temp=dijkstra(adj,n);\n\tmemset(memo,-1,sizeof(memo));\n\treturn dp(n,adj,temp);\n}\n``` | 1 | 0 | ['Dynamic Programming', 'C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Share My Java Dijkstra + DFS (w/ cache) Solution | share-my-java-dijkstra-dfs-w-cache-solut-vm6o | It took me a long time to understand the question...\n\n\n// Dijkstra + DFS with cache\npublic int countRestrictedPaths(int n, int[][] edges) {\n\tif (n <= 0 || | violinviolin | NORMAL | 2021-03-07T06:12:21.290388+00:00 | 2021-03-07T06:12:21.290445+00:00 | 70 | false | It took me a long time to understand the question...\n\n```\n// Dijkstra + DFS with cache\npublic int countRestrictedPaths(int n, int[][] edges) {\n\tif (n <= 0 || edges == null || edges.length == 0) return 0;\n\n\t// step 1. build graph\n\tMap<Integer, Map<Integer, Integer>> map = new HashMap<>(); // from -> {to -> weight}\n\tfor (int[] edge : edges) {\n\t\tmap.putIfAbsent(edge[0], new HashMap<>());\n\t\tmap.putIfAbsent(edge[1], new HashMap<>());\n\n\t\tmap.get(edge[0]).put(edge[1], edge[2]);\n\t\tmap.get(edge[1]).put(edge[0], edge[2]);\n\t} \n\n\t// step 2. Dijkstra \n\t// start from node n, to caluclate min distance from x to n\n\tint[] dist = new int[n+1]; // node 1 ~ n\n\tdist[n] = 0;\n\tPriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] - b[1]); // pq of {x, dist}\n\tpq.offer(new int[]{n, 0}); // start from n, weight is 0.\n\twhile (!pq.isEmpty()) {\n\t\tint[] cur = pq.poll();\n\t\tint node = cur[0];\n\t\tint weight = cur[1];\n\n\t\tMap<Integer, Integer> nexts = map.get(node);\n\t\tfor (int next : nexts.keySet()) {\n\t\t\tif (next == n) continue; // skip the final node\n\n\t\t\tint nextWeight = weight + nexts.get(next);\n\t\t\tif (dist[next] == 0 || nextWeight < dist[next]) {\n\t\t\t\tpq.offer(new int[]{next, nextWeight});\n\t\t\t\tdist[next] = nextWeight;\n\t\t\t}\n\t\t}\n\t}\n\n\t// step 3. DFS + cache to count restricted path\n\tint[] dp = new int[n+1];\n\tArrays.fill(dp, -1);\n\treturn dfs(1, n, map, dist, dp);\n}\n\nprivate int dfs(int node, int n, Map<Integer, Map<Integer, Integer>> map, int[] dist, int[] dp) {\n\tif (node == n) return 1; // reach n, means this is 1 restricted path\n\n\tif (dp[node] != -1) return dp[node];\n\n\tint count = 0;\n\tint weight = dist[node];\n\tMap<Integer, Integer> nexts = map.get(node);\n\tfor (int next : nexts.keySet()) {\n\t\tint nextWeight = dist[next];\n\t\tif (nextWeight < weight) {\n\t\t\tcount = (count + dfs(next, n, map, dist, dp)) % 1000000007;\n\t\t}\n\t}\n\n\tdp[node] = count;\n\treturn count;\n}\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | C++ dijastra + cached dfs 100% time/space | c-dijastra-cached-dfs-100-timespace-by-h-s9a8 | \n/*\n First, find out the shortest ditance between node x to node n.\n DFS to find restricted path.\n*/\ntypedef pair<long,int> pii;\nclass Solution {\np | halleywang | NORMAL | 2021-03-07T05:40:11.591127+00:00 | 2021-03-07T05:40:11.591159+00:00 | 117 | false | ```\n/*\n First, find out the shortest ditance between node x to node n.\n DFS to find restricted path.\n*/\ntypedef pair<long,int> pii;\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector<vector<int>>& edges) \n {\n vector<vector<pii>> graph(n+1,vector<pii>{});\n vector<long> dist(n+1,INT_MAX);\n dist[n]=0;\n for (auto edge:edges) {\n graph[edge[0]].push_back({edge[1],edge[2]});\n graph[edge[1]].push_back({edge[0],edge[2]});\n }\n priority_queue<pii,vector<pii>,greater<pii>> pq;\n pq.push({dist[n],n}); // dist, node\n while (!pq.empty()) {\n auto p=pq.top(); pq.pop();\n int u=p.second;\n for (pii vp:graph[u]) { //node, weight\n int v=vp.first, w=vp.second;\n if (dist[v]>dist[u]+w) {\n dist[v]=dist[u]+w;\n pq.push({dist[v],v});\n }\n }\n }\n vector<int> visited(n+1,-1);\n return dfs(graph,visited,dist,1,n,INT_MAX);\n }\n \n int dfs(vector<vector<pii>> &graph, vector<int> &visited, vector<long> &dist, int u, int n, long prev)\n {\n int mod=1e9+7;\n if (dist[u]>=prev) return 0;\n else if (visited[u]>=0) return visited[u];\n else if (u==n) return 1;\n int ret=0;\n for (auto vp:graph[u]) {\n ret=(ret%mod+dfs(graph,visited,dist,vp.first,n,dist[u])%mod)%mod;\n }\n visited[u]=ret;\n return ret;\n }\n};\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Python - Dijstra and DP DFS (No @lru_cache) | python-dijstra-and-dp-dfs-no-lru_cache-b-gbnm | python\nfrom heapq import heappush, heappop\n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = { i: | nuclearoreo | NORMAL | 2021-03-07T05:02:12.423099+00:00 | 2021-03-07T16:17:18.125150+00:00 | 68 | false | ```python\nfrom heapq import heappush, heappop\n\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = { i: [] for i in range(1, n + 1) }\n \n for u, v, w in edges:\n graph[u].append((v, w))\n graph[v].append((u, w))\n \n toLast = self.dijkstra(n, graph)\n \n return self.dfs(1, graph, toLast, {}) % (10 ** 9 + 7)\n \n def dijkstra(self, n: int, graph: dict) -> dict:\n shortest = { n: float(\'inf\') for n in range(1, n + 1) }\n shortest[n] = 0\n \n queue = [ (0, n) ]\n \n while queue:\n d, u = heappop(queue)\n \n for v, w in graph[u]:\n if shortest[v] > d + w:\n shortest[v] = d + w\n heappush(queue, (d + w, v))\n \n return shortest\n \n def dfs(self, u: int, graph: dict, toLast: dict, seen: dict) -> int:\n if u == len(graph):\n return 1\n \n if u in seen:\n return seen[u]\n \n res = 0\n for v, _ in graph[u]:\n if toLast[u] > toLast[v]:\n res += self.dfs(v, graph, toLast, seen)\n \n seen[u] = res\n return seen[u]\n``` | 1 | 1 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | c++ djkstra readable code | c-djkstra-readable-code-by-cxky-1pg2 | \nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dfs(int n, vector<int> &dp, vector<int> &dist, vector<vector<pair<int,int>>> &graph, int d) {\n | cxky | NORMAL | 2021-03-07T04:41:10.651319+00:00 | 2021-03-07T04:44:20.695720+00:00 | 91 | false | ```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dfs(int n, vector<int> &dp, vector<int> &dist, vector<vector<pair<int,int>>> &graph, int d) {\n if(n == 1) \n return 1;\n long ans = 0;\n if(dp[n] != -1) \n return dp[n];\n\n for(auto [i, w]: graph[n]) {\n if(d < dist[i]) {\n ans += dfs(i, dp, dist, graph, dist[i]) % mod; \n ans %= mod;\n }\n }\n return dp[n] = ans;\n }\n void shortestPath(int n, vector<vector<pair<int,int>>> &graph, vector<int> &dist) {\n set<pair<int,int>> pq;\n pq.insert({0, n});\n while(!pq.empty()) {\n auto [wgt, node] = *begin(pq);\n pq.erase(pq.begin());\n for(auto [i, w] : graph[node]) { \n if(dist[i] > wgt + w) {\n dist[i] = wgt + w;\n pq.insert({dist[i], i});\n }\n }\n }\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int, int>>> graph(n + 1);\n vector<int> dp(n + 1, -1);\n vector<int> dist(n + 1, INT_MAX);\n dist[n] = 0;\n for (auto &e : edges) {\n graph[e[0]].push_back({e[1], e[2]});\n graph[e[1]].push_back({e[0], e[2]});\n }\n shortestPath(n, graph, dist);\n return dfs(n, dp, dist, graph, 0);\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra's shortest paths for each node, then DFS + Memo, O(V + E * log V) | dijkstras-shortest-paths-for-each-node-t-awch | find each node shortest distance to node n;\n2. dfs from n to 1, + memoization, to get total number of paths;\n\nSortedList, O(log n) remove.\n\ntime: O(V + E * | goodgoodwish | NORMAL | 2021-03-07T04:39:08.267497+00:00 | 2021-03-07T04:47:53.801842+00:00 | 238 | false | 1. find each node shortest distance to node n;\n2. dfs from n to 1, + memoization, to get total number of paths;\n\nSortedList, O(log n) remove.\n\ntime: O(V + E * log V).\nhttps://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\n\n```\nfrom sortedcontainers import SortedList, SortedDict, SortedSet\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n # 1. find each node dist to n\n # 2. dfs from n to 1, + memoization.\n g = defaultdict(list)\n for u, v, w in edges:\n g[u].append((w, v))\n g[v].append((w, u))\n d = defaultdict(int)\n for i in range(1, n+1):\n d[i] = float("inf")\n d[n] = 0\n \n h = SortedList([(0,n)])\n while h:\n dist, u = h.pop(0)\n # print(u, "dist:", dist)\n for w, v in g[u]:\n if dist + w < d[v]:\n h.discard((d[v], v))\n d[v] = dist + w\n h.add((d[v], v))\n # print(d)\n f = {}\n ans = self.dfs(g, d, n, f)\n \n return ans\n \n def dfs(self, g, d, u, f):\n if u == 1:\n return 1\n ans = 0\n MOD = 10**9 + 7\n if u in f:\n return f[u]\n for _, v in g[u]:\n if d[v] > d[u]:\n ans += self.dfs(g, d, v, f)\n \n f[u] = ans % MOD\n return f[u]\n``` | 1 | 0 | ['Python'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Java, Dijikstra + DFS with memo | java-dijikstra-dfs-with-memo-by-fighting-v4ah | \nLong[] cache;\n public int countRestrictedPaths(int n, int[][] edges) {\n cache=new Long[n+1];\n Map<Integer,Map<Integer,Integer>> graph=new | fighting_for_flag | NORMAL | 2021-03-07T04:09:10.234923+00:00 | 2021-03-07T04:10:12.074775+00:00 | 225 | false | ```\nLong[] cache;\n public int countRestrictedPaths(int n, int[][] edges) {\n cache=new Long[n+1];\n Map<Integer,Map<Integer,Integer>> graph=new HashMap<>();\n for(int[] edge:edges){\n graph.computeIfAbsent(edge[0],k->new HashMap<>()).put(edge[1],edge[2]);\n graph.computeIfAbsent(edge[1],k->new HashMap<>()).put(edge[0],edge[2]);\n }\n int[] dis=new int[n+1];\n Arrays.fill(dis,Integer.MAX_VALUE);\n dis[n]=0;\n PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(a[1]-b[1]));\n pq.add(new int[]{n,0});\n while(!pq.isEmpty()){\n int[] cur=pq.poll();\n Map<Integer,Integer> children=graph.get(cur[0]);\n if(children==null) continue;\n for(int child:children.keySet()){\n if(dis[child]>cur[1]+children.get(child))\n {\n dis[child]=cur[1]+children.get(child);\n pq.add(new int[]{child,dis[child]});\n }\n }\n }\n\t\t//**since there are many duplicate states, BFS can\'t pass OJ**\n // long res=0,mod=(long)1e9+7;\n // Queue<int[]> queue=new LinkedList<>();\n // queue.add(new int[]{n,0});\n // while(!queue.isEmpty()){\n // int[] cur=queue.poll();\n // if(cur[0]==1) {\n // res=(res+1)%mod;\n // continue;\n // }\n // Map<Integer,Integer> children=graph.get(cur[0]);\n // if(children==null) continue;\n // for(int child:children.keySet()){\n // if(dis[child]>cur[1])\n // queue.add(new int[]{child,dis[child]});\n // }\n // }\n return (int)dfs(n,graph,0,dis);\n \n }\n \n public long dfs(int cur,Map<Integer,Map<Integer,Integer>> graph,int dis,int[] distance){\n if(cur==1) return 1;\n if(cache[cur]!=null) return cache[cur];\n Map<Integer,Integer> children=graph.get(cur);\n long res=0,mod=(long)1e9+7;\n if(children!=null) {\n for(int child:children.keySet()){\n if(distance[child]>dis)\n res=(res+dfs(child,graph,distance[child],distance))%mod;\n } \n }\n cache[cur]=res;\n return res;\n }\n``` | 1 | 1 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | Clean Java | clean-java-by-rexue70-hcfo | This question is a combination of \n\n1. 787. Cheapest Flights Within K Stops https://leetcode.com/problems/cheapest-flights-within-k-stops/\n2. cout of increas | rexue70 | NORMAL | 2021-03-07T04:06:48.781342+00:00 | 2021-03-07T04:08:05.131266+00:00 | 145 | false | This question is a combination of \n\n1. 787. Cheapest Flights Within K Stops https://leetcode.com/problems/cheapest-flights-within-k-stops/\n2. cout of increasing path\n\n\nwe first use dijikstra to calculate the distance to last node value of every node\nthen we do a dfs from 1 to n, use memo to cache.\n\n```\nclass Solution {\n long res = 0L;\n int MOD = (int)1e9 + 7;\n int n;\n Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();\n Map<Integer, Integer> distanceToLastNode = new HashMap<>();\n public int countRestrictedPaths(int n, int[][] edges) {\n this.n = n;\n for (int[] edge : edges) {\n graph.computeIfAbsent(edge[0], value -> new HashMap<>()).put(edge[1], edge[2]);\n graph.computeIfAbsent(edge[1], value -> new HashMap<>()).put(edge[0], edge[2]);\n }\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n pq.add(new int[] {0, n}); //{distance, city}\n while (!pq.isEmpty()) {\n int[] cur = pq.poll();\n int city = cur[1], distance = cur[0];\n if (!distanceToLastNode.containsKey(city)) distanceToLastNode.put(city, distance);\n else if (distanceToLastNode.get(city) <= distance) continue;\n Map<Integer, Integer> neighbors = graph.getOrDefault(city, new HashMap<>());\n for (int nei : neighbors.keySet()) \n pq.add(new int[] {distance + neighbors.get(nei), nei}); \n }\n return dfs(1);\n }\n Map<Integer, Integer> memo = new HashMap<>();\n private int dfs(int city) {\n if (city == n) return 1;\n if (memo.containsKey(city)) return memo.get(city);\n Map<Integer, Integer> neighbors = graph.getOrDefault(city, new HashMap<>());\n int count = 0;\n for (int nei : neighbors.keySet())\n if (distanceToLastNode.get(nei) < distanceToLastNode.get(city))\n count = (count + dfs(nei)) % MOD;\n memo.put(city, count);\n return count;\n }\n}\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | [C++] BFS + DP | c-bfs-dp-by-louis1992-s1ru | \nclass Solution {\npublic:\n \n void bfs(int n, const vector<vector<pair<int, int>>>& graph, vector<int>& distances, vector<int>& closest_nodes) {\n | louis1992 | NORMAL | 2021-03-07T04:02:51.422994+00:00 | 2021-03-07T04:53:01.222272+00:00 | 261 | false | ```\nclass Solution {\npublic:\n \n void bfs(int n, const vector<vector<pair<int, int>>>& graph, vector<int>& distances, vector<int>& closest_nodes) {\n auto cmp = [](const pair<int, int> &a, const pair<int, int> &b) {\n return a.second > b.second;\n };\n priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);\n vector<bool> visited(n+1, false);\n pq.push({n, 0});\n \n while (!pq.empty()) {\n pair<int, int> current = pq.top();\n pq.pop();\n int node = current.first;\n int dis = current.second;\n if (visited[node] == true) {\n continue;\n }\n distances[node] = dis;\n visited[node] = true;\n closest_nodes.push_back(node);\n \n for (pair<int, int> neighbor : graph[node]) {\n int neighbor_node = neighbor.first;\n if (visited[neighbor_node] == false) {\n pq.push({neighbor_node, dis + neighbor.second});\n }\n }\n }\n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int, int>>> graph(n+1);\n for (const vector<int>& edge : edges) {\n graph[edge[0]].push_back({edge[1], edge[2]});\n graph[edge[1]].push_back({edge[0], edge[2]});\n }\n \n vector<int> distances(n + 1, 0);\n vector<int> closest_nodes;\n bfs(n, graph, distances, closest_nodes);\n \n vector<long> dp(n+1, 0);\n dp[1] = 1;\n int mod = 1e9+7;\n for (int i = closest_nodes.size() - 1; i >= 0; i--) {\n int node = closest_nodes[i];\n for (pair<int, int> neighbor : graph[node]) {\n int neighbor_node = neighbor.first;\n if (distances[neighbor_node] < distances[node]) {\n dp[neighbor_node] += dp[node];\n dp[neighbor_node] %= mod;\n }\n }\n }\n \n return dp[n];\n }\n};\n``` | 1 | 0 | ['C'] | 1 |
number-of-restricted-paths-from-first-to-last-node | Simple dijkstra's/dfs with dp | simple-dijkstrasdfs-with-dp-by-nikhilc15-edng | cpp\nclass Solution {\npublic:\n void dijkstra(vector<vector<pair<int, int>>> &adj, vector<int> &dists) {\n vector<bool> seen(adj.size(), false);\n | nikhilc1527 | NORMAL | 2021-03-07T04:02:49.753363+00:00 | 2021-03-07T04:03:32.719098+00:00 | 226 | false | ```cpp\nclass Solution {\npublic:\n void dijkstra(vector<vector<pair<int, int>>> &adj, vector<int> &dists) {\n vector<bool> seen(adj.size(), false);\n auto comp = [&dists](int a, int b) {return dists[a]>dists[b];};\n priority_queue<int, vector<int>, decltype(comp)> pq(comp);\n pq.push(adj.size()-1);\n dists[adj.size()-1] = 0;\n while (!pq.empty()) {\n int a = pq.top();\n pq.pop();\n for (auto [b, w] : adj[a]) {\n if (dists[b] > dists[a]+w) {\n dists[b] = dists[a] + w;\n pq.push(b);\n }\n }\n }\n }\n \n int dfs(vector<vector<pair<int, int>>> &adj, vector<int> &dists, int a, vector<bool> &seen, vector<int> &dp) {\n if (seen[a]) return 0;\n if (dp[a]) return dp[a];\n seen[a] = true;\n int res = 0;\n for (auto [b, w] : adj[a]) {\n if (dists[b]>=dists[a]||dists[a]==0) continue;\n else if (b == adj.size()-1) {\n ++res;\n } else {\n res = (res + dfs(adj, dists, b, seen,dp))%((int)1e9+7);\n }\n }\n seen[a] = false;\n return dp[a] = res;\n } \n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n vector<vector<pair<int, int>>> adj(n+1);\n for (auto &i : edges) {\n int a = i[0], b = i[1], w = i[2];\n adj[a].emplace_back(b,w);\n adj[b].emplace_back(a, w);\n }\n \n vector<int> dists(n+1, INT_MAX);\n dijkstra(adj, dists);\n \n vector<bool> seen(n+1, false);\n vector<int> dp(n+1, 0);\n return dfs(adj, dists, 1, seen,dp);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'C'] | 0 |
number-of-restricted-paths-from-first-to-last-node | JavaScript Djikstras + Memoization | javascript-djikstras-memoization-by-stev-2gu5 | javascript\nvar countRestrictedPaths = function(n, edges) {\n // create an adjacency list to store the neighbors with weight for each node\n const adjList | stevenkinouye | NORMAL | 2021-03-07T04:02:20.073616+00:00 | 2021-03-07T04:06:14.455438+00:00 | 228 | false | ```javascript\nvar countRestrictedPaths = function(n, edges) {\n // create an adjacency list to store the neighbors with weight for each node\n const adjList = new Array(n + 1).fill(null).map(() => new Array(0));\n for (const [node1, node2, weight] of edges) {\n adjList[node1].push([node2, weight]);\n adjList[node2].push([node1, weight]);\n }\n \n // using djikstras algorithm\n // find the shortest path from n to each node\n const nodeToShortestPathDistance = {}\n const heap = new Heap();\n heap.push([n, 0])\n let numNodeSeen = 0;\n while (numNodeSeen < n) {\n const [node, culmativeWeight] = heap.pop();\n if (nodeToShortestPathDistance.hasOwnProperty(node)) {\n continue;\n }\n nodeToShortestPathDistance[node] = culmativeWeight;\n numNodeSeen++;\n for (const [neighbor, edgeWeight] of adjList[node]) {\n if (nodeToShortestPathDistance.hasOwnProperty(neighbor)) {\n continue;\n }\n heap.push([neighbor, edgeWeight + culmativeWeight]);\n }\n }\n \n\n // do a DFS caching the number of paths for each node\n // so that we don\'t need to redo the number of paths again\n // when we visit that node through another path\n const nodeToNumPaths = {};\n const dfs = (node) => {\n if (node === n) return 1;\n if (nodeToNumPaths.hasOwnProperty(node)) {\n return nodeToNumPaths[node];\n }\n let count = 0;\n for (const [neighbor, weight] of adjList[node]) {\n if (nodeToShortestPathDistance[node] > nodeToShortestPathDistance[neighbor]) {\n count += dfs(neighbor);\n }\n }\n return nodeToNumPaths[node] = count % 1000000007;\n }\n return dfs(1);\n};\n\nclass Heap {\n constructor() {\n this.store = [];\n }\n \n peak() {\n return this.store[0];\n }\n \n size() {\n return this.store.length;\n }\n \n pop() {\n if (this.store.length < 2) {\n return this.store.pop();\n }\n const result = this.store[0];\n this.store[0] = this.store.pop();\n this.heapifyDown(0);\n return result;\n }\n \n push(val) {\n this.store.push(val);\n this.heapifyUp(this.store.length - 1);\n }\n \n heapifyUp(child) {\n while (child) {\n const parent = Math.floor((child - 1) / 2);\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n child = parent;\n } else {\n return child;\n }\n }\n }\n \n heapifyDown(parent) {\n while (true) {\n let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n if (this.shouldSwap(child2, child)) {\n child = child2\n }\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n parent = child;\n } else {\n return parent;\n }\n }\n }\n \n shouldSwap(child, parent) {\n return child && this.store[child][1] < this.store[parent][1];\n }\n}\n``` | 1 | 0 | ['Dynamic Programming', 'JavaScript'] | 0 |
number-of-restricted-paths-from-first-to-last-node | Dijkstra + DFS + DP (Does it get any better than this) | dijkstra-dfs-dp-does-it-get-any-better-t-kpfh | \nclass Solution {\n int MOD = (int) (Math.pow(10, 9) + 7);\n public int countRestrictedPaths(int n, int[][] edges) {\n Map<Integer, List<int[]>> g | banty | NORMAL | 2021-03-07T04:01:03.236608+00:00 | 2021-03-07T04:01:03.236657+00:00 | 284 | false | ```\nclass Solution {\n int MOD = (int) (Math.pow(10, 9) + 7);\n public int countRestrictedPaths(int n, int[][] edges) {\n Map<Integer, List<int[]>> graph = new HashMap<>();\n for (int[] edge : edges) {\n int from = edge[0];\n int to = edge[1];\n int dist = edge[2];\n\n graph.putIfAbsent(from, new ArrayList<>());\n graph.get(from).add(new int[]{to, dist});\n\n graph.putIfAbsent(to, new ArrayList<>());\n graph.get(to).add(new int[]{from, dist});\n }\n\n int[] distances = new int[n + 1];\n\n Arrays.fill(distances, Integer.MAX_VALUE);\n distances[n] = 0;\n\n boolean[] visited = new boolean[n + 1];\n PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));\n pq.offer(new int[]{n, 0});\n\n while (!pq.isEmpty()) {\n int[] shortestDistanceNode = pq.poll();\n int curr = shortestDistanceNode[0];\n int dist = shortestDistanceNode[1];\n visited[curr] = true;\n\n if (distances[curr] < dist) {\n //if we have already found a better distance, no need to add it again\n continue;\n }\n\n for (int[] edge : graph.get(curr)) {\n int next = edge[0];\n int weight = edge[1];\n if (!visited[next]) {\n int newDistance = distances[curr] + weight;\n\n // edge relaxation\n if (newDistance < distances[next]) {\n distances[next] = newDistance;\n pq.offer(new int[]{next, newDistance});\n }\n }\n }\n\n }\n\n// System.out.println(Arrays.toString(distances));\n\n Map<Integer, Long> dp = new HashMap<>();\n long count = dfs(graph, n, 1, distances, dp);\n \n return (int) (count % MOD);\n }\n\n private long dfs(Map<Integer, List<int[]>> graph, int n, int currentVertex, int[] distances, Map<Integer, Long> dp) {\n if (currentVertex == n) return 1;\n\n if (dp.containsKey(currentVertex)) return dp.get(currentVertex);\n\n long count = 0;\n\n for (int[] edge : graph.get(currentVertex)) {\n int next = edge[0];\n if (distances[currentVertex] > distances[next]) {\n count += (dfs(graph, n, next, distances, dp) % MOD);\n }\n }\n dp.put(currentVertex, count);\n return count;\n }\n}\n``` | 1 | 0 | [] | 0 |
number-of-restricted-paths-from-first-to-last-node | c++ dynamic programming(memoization+dfs) + dijktra's algorithm.. | c-dynamic-programmingmemoizationdfs-dijk-uq66 | // c++ dynamic programming + dijktra\'s algorithm..\n// step1--> use dijktra\'s shortest path algorithm to obtain shortes distance of all node from "nth node ie | Kumar_Neelesh | NORMAL | 2021-03-07T04:00:36.530336+00:00 | 2021-03-07T05:06:26.836509+00:00 | 284 | false | // c++ dynamic programming + dijktra\'s algorithm..\n// step1--> use dijktra\'s shortest path algorithm to obtain shortes distance of all node from "nth node ie last node"..\n// step 2---> run dfs from nth to 1st node with condition distanceToLastNode(zi) > distanceToLastNode(zi+1)...\n// step 3--->store dp[node number] as it indicate number of path from node "node number " to first ie 1th node ,utilise stored result if same node is again came in path.\n\n// below is my code .. do upvote if you like my approach.. :)\n\n\n \n int dis[20001];\n \n int dp[20001];\n \n int M=1e9+7;\n \n void dijkatras(int n,vector<pair<int,int>> adlist[])\n {\n vector<int> vis(n+1,-1);\n \n vis[n]=1;\n dis[n]=0;\n set<pair<int,int>> pq;\n pq.insert(make_pair(0,n));\n \n while(pq.empty()==false)\n {\n auto it=*(pq.begin());\n pq.erase(pq.begin());\n \n for(auto i:adlist[it.second])\n {\n if(dis[i.first]>dis[it.second]+i.second)\n {\n auto ptr=pq.find(make_pair(dis[i.first],i.first));\n \n if(ptr!=pq.end()) pq.erase(ptr);\n \n dis[i.first]=dis[it.second]+i.second;\n pq.insert(make_pair(dis[i.first],i.first));\n }\n }\n }\n }\n \n \n \n \n long long int dfs(int n,vector<pair<int,int>> adlist[],int d)\n {\n \n if(n==1) return 1;\n \n int ans=0;\n \n if(dp[n]!=-1) return dp[n];\n \n for(auto i:adlist[n])\n {\n if(d<dis[i.first]) ans =(ans%M+dfs(i.first,adlist,dis[i.first])%M)%M;//distanceToLastNode(zi) > distanceToLastNode(zi+1) condition \n }\n return dp[n]= ans;\n \n }\n \n int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n \n for(int i=1;i<=n;i++) dis[i]=INT_MAX;\n \n for(int i=1;i<=n;i++) dp[i]=-1;\n \n vector<pair<int,int>> adlist[n+1];\n \n for(auto i:edges)\n {\n adlist[i[0]].push_back(make_pair(i[1],i[2]));\n adlist[i[1]].push_back(make_pair(i[0],i[2]));\n }\n \n \n dijkatras(n,adlist);\n \n \n return dfs(n,adlist,0);\n \n \n \n return 0;\n \n }\n} | 1 | 1 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.