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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
path-sum | Python || Dfs || binary tree leaves find all paths | python-dfs-binary-tree-leaves-find-all-p-holi | It is intuitive to find all the possible paths from roots to leaves and sum them and check with the target sum.\n\nclass Solution:\n def hasPathSum(self, roo | ana_2kacer | NORMAL | 2022-07-03T07:02:21.614449+00:00 | 2022-07-03T07:02:21.614493+00:00 | 432 | false | It is intuitive to find all the possible paths from roots to leaves and sum them and check with the target sum.\n```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n res = []\n if not root:\n return False\n def dfs(r,path):\n if not r.left and not r.right:\n path+=[r.val]\n res.append(path)\n return\n if r.left:\n dfs(r.left,path+[r.val])\n if r.right:\n dfs(r.right,path+[r.val])\n return \n dfs(root,[])\n # print(res)\n for arr in res:\n if sum(arr)==targetSum:\n return True\n return False\n```\n```\nUPVOTE IF YOU LIKED IT :)\n```\nDo Let me know how we can optimise this further.\nOne way i know that instead of keeping path, we can keep the sum itself and then return true if found targetSum.\nBut for me it does not change time complexity much. \n | 8 | 0 | ['Depth-First Search', 'Recursion', 'Python', 'Python3'] | 1 |
path-sum | Python/JS/Go/C++ O(n) DFS [w/ Hint ] 有中文解題文章 | pythonjsgoc-on-dfs-w-hint-you-zhong-wen-xrckw | \u6709\u4E2D\u6587\u89E3\u984C\u6587\u7AE0\n\nPython O(n) sol by DFS\n\n---\nHint:\n\nThink of DFS algorithm framework\n\nOne node is the so-called leaf node, i | brianchiang_tw | NORMAL | 2020-03-01T07:40:41.063832+00:00 | 2024-01-29T12:35:38.339368+00:00 | 1,165 | false | [\u6709\u4E2D\u6587\u89E3\u984C\u6587\u7AE0](https://vocus.cc/article/65b77662fd8978000192c491)\n\nPython O(n) sol by DFS\n\n---\n**Hint**:\n\nThink of **DFS** algorithm framework\n\nOne node is the so-called **leaf node**, if and only if,\nit is **not an empty node** and it **doesn\'t have** both *left child* and *right child*.\n\nImagine the path sum as a process treasure hunt **from root to leaf** with specified target value\n\nUpdate *target value* as *previous target* - *current node value*, then go down to next level in DFS.\n\n\n---\n**Implementation_#1**:\nDFS with recursion\n\n```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n \n ## Base case\n if not root:\n return False\n \n ## Base case\n if not root.left and not root.right:\n \n # we have the path with targetSum\n return targetSum == root.val\n \n ## General case:\n return self.hasPathSum(root.left, targetSum - root.val) or \\\n self.hasPathSum(root.right, targetSum - root.val)\n```\n\n---\n\nin **Javascript**:\n\n<details>\n\t<summary> Expand to see source code </summary>\n\n```\nvar hasPathSum = function(root, targetSum) {\n \n // Base case\n if( null == root ){\n return false;\n }\n \n \n if( null == root.left && null == root.right ){\n // Base case\n return root.val == targetSum;\n }else{\n \n // General cases\n return hasPathSum( root.left, targetSum-root.val ) || hasPathSum( root.right, targetSum-root.val );\n }\n};\n```\n\n</details>\n\n---\n\nin **Go**:\n\n<details>\n\t<summary> Expand to see source code </summary>\n\t\n```\nfunc hasPathSum(root *TreeNode, targetSum int) bool {\n \n // Base case\n if nil == root{\n return false\n }\n \n \n if nil == root.Left && nil == root.Right{\n // Base case\n return root.Val == targetSum\n \n }else{\n // General cases\n return hasPathSum(root.Left, targetSum - root.Val) || hasPathSum(root.Right, targetSum - root.Val)\n }\n}\n```\n\n</details>\n\n---\n\nin **C++**\n\n<details>\n\t<summary> Expand to see source code </summary>\n\t\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n \n if ( NULL == root ){\n return false;\n }\n \n if ( NULL == root->left && NULL == root->right){\n return root->val == targetSum;\n }else{\n return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);\n }\n }\n};\n```\n</details>\n\n---\n**Implementation_#2**:\nDFS with stack\n\n```\nclass Solution:\n \n def hasPathSum(self, root, sum):\n \n traversal_stack = [(root, sum)]\n \n # DFS with stack\n while traversal_stack:\n \n node, value = traversal_stack.pop()\n \n if node:\n if not node.left and not node.right and node.val == value:\n # leaf node\n return True\n \n else:\n # non-leaf node\n traversal_stack.append((node.right, value-node.val))\n traversal_stack.append((node.left, value-node.val))\n\n else:\n # empty node\n continue\n \n return False\n```\n\n---\n\n\n---\n\nRelated leetcode challenge:\n\n[1] [Leetcode #113 Path Sum II](https://leetcode.com/problems/path-sum-ii/)\n\n[2] [Leetcode #437 Path Sum III](https://leetcode.com/problems/path-sum-iii/)\n\n[3] [Leetcode #129 Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | 8 | 1 | ['Stack', 'Depth-First Search', 'Recursion', 'C', 'Python', 'C++', 'Go', 'JavaScript'] | 0 |
path-sum | Go 4ms | go-4ms-by-dynasty919-fq7m | \nfunc hasPathSum(root *TreeNode, sum int) bool {\n if root == nil {\n return false\n }\n if root.Left == nil && root.Right == nil {\n re | dynasty919 | NORMAL | 2020-02-24T13:52:03.754115+00:00 | 2020-02-24T13:52:03.754158+00:00 | 367 | false | ```\nfunc hasPathSum(root *TreeNode, sum int) bool {\n if root == nil {\n return false\n }\n if root.Left == nil && root.Right == nil {\n return sum == root.Val\n }\n return hasPathSum(root.Left, sum - root.Val) || hasPathSum(root.Right, sum - root.Val)\n}\n``` | 8 | 0 | [] | 1 |
path-sum | Simple Python solution, recursive and iterative (using DFS) | simple-python-solution-recursive-and-ite-vejc | Recursive\n\n\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n \n s | johanndiedrick | NORMAL | 2019-10-21T20:25:24.412698+00:00 | 2019-10-21T20:25:24.412749+00:00 | 960 | false | **Recursive**\n\n```\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n \n sum = sum - root.val\n \n if not root.left and not root.right: #leaf node\n return sum == 0\n else:\n return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)\n```\n\t\t\t\n**Iterative**\n\n``` \nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n \n if not root:\n return False\n \n stack = []\n \n stack.append((root, sum - root.val))\n \n while stack:\n node, sum = stack.pop()\n if not node.left and not node.right and sum == 0:\n return True\n if node.left:\n stack.append((node.left, sum - node.left.val))\n if node.right:\n stack.append((node.right, sum - node.right.val)) \n return False\n``` | 8 | 0 | ['Tree', 'Depth-First Search', 'Recursion', 'Iterator', 'Python'] | 2 |
path-sum | JavaScript-Easy top-bottom approach. | javascript-easy-top-bottom-approach-by-l-7je6 | \nvar hasPathSum = function(root, sum) {\n if (!root) return false;\n let queue = [root];\n while (queue.length > 0) {\n let cur = queue.shift() | lazy_tym | NORMAL | 2019-09-23T15:33:48.885097+00:00 | 2019-09-23T15:33:48.885130+00:00 | 1,124 | false | ```\nvar hasPathSum = function(root, sum) {\n if (!root) return false;\n let queue = [root];\n while (queue.length > 0) {\n let cur = queue.shift();\n if (!cur.left && !cur.right && cur.val == sum) {\n return true;\n }\n if (cur.left) {\n cur.left.val += cur.val;\n queue.push (cur.left);\n }\n if (cur.right) {\n cur.right.val += cur.val;\n queue.push (cur.right);\n }\n }\n return false;\n};\n\nfunction TreeNode (val) {\n this.val = val;\n this.left = this.right = null;\n}\n``` | 8 | 0 | ['JavaScript'] | 3 |
path-sum | Just another java solution, recursive. simple but can be simpler. | just-another-java-solution-recursive-sim-rbz5 | /**\n * Definition for binary tree\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * T | salg | NORMAL | 2014-11-26T04:12:03+00:00 | 2014-11-26T04:12:03+00:00 | 1,259 | false | /**\n * Definition for binary tree\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n public class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n //start it off with initial sum of 0, pass in root.\n return helper(root,0,sum);\n }\n \n public boolean helper(TreeNode node,int currSum,int wanted){\n if(node==null)\n return false;\n \n //node is a leaf\n if(node.left==null && node.right==null){\n if((node.val+currSum) == wanted) //check if it sumeed up.\n return true;\n return false;\n }\n \n //not a leaf, so recursively try again but with child nodes, pass in current sum + val of this node.\n return (helper(node.left,currSum+node.val,wanted) || helper(node.right,currSum+node.val,wanted));\n \n }\n } | 8 | 0 | [] | 2 |
path-sum | 12ms C++ solution | 12ms-c-solution-by-pjlloyd100-dhuc | class Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL) return false;\n sum -= root->val;\n | pjlloyd100 | NORMAL | 2015-07-06T15:54:23+00:00 | 2015-07-06T15:54:23+00:00 | 1,727 | false | class Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL) return false;\n sum -= root->val;\n return sum == 0 && root->left == NULL && root->right == NULL ? true : hasPathSum(root->left, sum) | hasPathSum(root->right, sum);\n }\n }; | 8 | 0 | [] | 2 |
path-sum | My Java solution using Recursive | my-java-solution-using-recursive-by-viol-5pm2 | \n public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null) {\n return false;\n } else {\n if (root.left = | violinn | NORMAL | 2015-10-24T08:56:43+00:00 | 2015-10-24T08:56:43+00:00 | 1,025 | false | \n public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null) {\n return false;\n } else {\n if (root.left == null && root.right == null) {\n return sum == root.val;\n } else {\n int subSum = sum - root.val;\n return hasPathSum(root.left, subSum) || hasPathSum(root.right, subSum);\n }\n }\n } | 8 | 0 | [] | 0 |
path-sum | Simple c++ solution | simple-c-solution-by-xjq-nqiz | class Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL){\n return false;\n }\n | xjq | NORMAL | 2016-04-28T03:45:23+00:00 | 2016-04-28T03:45:23+00:00 | 1,404 | false | class Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL){\n return false;\n }\n int newsum = sum - root->val;\n if(root->left == NULL && root->right == NULL){\n return newsum == 0;\n }\n return hasPathSum(root->left, newsum) || hasPathSum(root->right, newsum);\n }\n }; | 8 | 0 | ['C++'] | 0 |
path-sum | Path Sum [C++] | path-sum-c-by-moveeeax-e510 | IntuitionThe problem requires determining if there is a path from the root to a leaf node where the sum of the node values equals a target sum. This can be visu | moveeeax | NORMAL | 2025-01-28T13:11:16.178935+00:00 | 2025-01-28T13:11:16.178935+00:00 | 948 | false | # Intuition
The problem requires determining if there is a path from the root to a leaf node where the sum of the node values equals a target sum. This can be visualized as a decision tree, where at each node we decide to explore either the left or right subtree. If a path exists that satisfies the condition, we return `true`.
# Approach
1. **Base Case**:
- If the root is `null`, return `false` because there's no path.
- If the current node is a leaf (no left or right children), check if the node's value equals the remaining target sum.
2. **Recursive Case**:
- Subtract the current node's value from the target sum.
- Recursively check both the left and right subtrees.
- If either subtree has a valid path, return `true`.
3. **Termination**:
- The recursion terminates either when we reach a leaf node or determine no valid path exists in both subtrees.
# Complexity
- **Time Complexity**:
$$O(n)$$
Each node is visited once, where `n` is the number of nodes in the tree.
- **Space Complexity**:
$$O(h)$$
The recursion stack depth is proportional to the height of the tree, where `h` is the height. In the worst case (skewed tree), this could be `O(n)`.
# Code
```cpp
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return root->val == targetSum;
return hasPathSum(root->left, targetSum - root->val) ||
hasPathSum(root->right, targetSum - root->val);
}
};
``` | 7 | 0 | ['C++'] | 0 |
path-sum | ✅26ms | 99.64% | Easy Solution | Recursive Solution | 3 lines of code | 26ms-9964-easy-solution-recursive-soluti-q82b | Intuition\nThe problem asks us to determine if there is a root-to-leaf path in a binary tree that sums up to a given target sum. My first thought was to recursi | CodeWithCharan | NORMAL | 2024-08-29T12:51:48.635687+00:00 | 2024-08-29T12:51:48.635715+00:00 | 867 | false | # Intuition\nThe problem asks us to determine if there is a root-to-leaf path in a binary tree that sums up to a given target sum. My first thought was to recursively explore each path from the root to the leaf nodes, keeping track of the remaining sum as we traverse down the tree. If we reach a leaf node and the remaining sum equals the leaf node\'s value, it means we\'ve found a valid path.\n\n# Approach\n1. **Base Case**: If the current node is `None`, return `False` because there\'s no path to explore.\n2. **Leaf Node Check**: If the current node is a leaf (i.e., both `root.left` and `root.right` are `None`), check if the remaining sum (`targetSum - root.val`) is `0`. If it is, return `True`.\n3. **Recursive Case**: If the current node is not a leaf, subtract the current node\'s value from the `targetSum` and recursively check the left and right subtrees. If either subtree has a valid path, return `True`.\n4. The function ultimately returns `True` if there is at least one root-to-leaf path that sums to `targetSum`, otherwise, it returns `False`.\n\n# Complexity\n- Time complexity:\n The time complexity is $$O(n)$$, where `n` is the number of nodes in the tree. This is because, in the worst case, we might need to visit all nodes to find a valid path or to determine that no valid path exists.\n\n- Space complexity:\n The space complexity is $$O(h)$$, where `h` is the height of the tree. This is due to the recursive call stack. In the worst case of an unbalanced tree, the height `h` can be `n`, making the space complexity $$O(n)$$.\n\n---\n\n# Code\n```python3 []\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n # 1. base case\n if not root: return False\n # 2. check if its leaf node\n if not root.left and not root.right: return targetSum - root.val == 0\n # 3. Recursive case\n return self.hasPathSum(root.left, targetSum-root.val) or self.hasPathSum(root.right, targetSum-root.val)\n``` | 7 | 0 | ['Tree', 'Depth-First Search', 'Recursion', 'Binary Tree', 'Python3'] | 2 |
path-sum | easy go solution | easy-go-solution-by-debasmitasaha23-p3f2 | 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 | debasmitasaha23 | NORMAL | 2022-12-08T07:44:59.148481+00:00 | 2022-12-08T07:44:59.148518+00:00 | 571 | 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```\n/**\n * Definition for a binary tree node.\n * type TreeNode struct {\n * Val int\n * Left *TreeNode\n * Right *TreeNode\n * }\n */\n\n\n\nfunc hasPathSum(root *TreeNode, targetSum int) bool {\n if root == nil {\n return false\n }\n if root.Left == nil && root.Right == nil {\n return targetSum == root.Val\n }\n return hasPathSum(root.Left, targetSum - root.Val) || hasPathSum(root.Right, targetSum - root.Val)\n \n}\n\n\n``` | 7 | 0 | ['Go'] | 0 |
path-sum | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | ontimebeats-9997-memoryspeed-0ms-may-202-8988 | \n\n\n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\nTake care broth | darian-catalin-cucer | NORMAL | 2022-05-15T04:22:47.667078+00:00 | 2022-05-15T04:22:47.667104+00:00 | 1,234 | false | ```\n```\n\n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* ***Java***\n```\npublic boolean hasPathSum(TreeNode root, int sum) {\n // iteration method\n if (root == null) {return false;}\n Stack<TreeNode> path = new Stack<>();\n Stack<Integer> sub = new Stack<>();\n path.push(root);\n sub.push(root.val);\n while (!path.isEmpty()) {\n TreeNode temp = path.pop();\n int tempVal = sub.pop();\n if (temp.left == null && temp.right == null) {if (tempVal == sum) return true;}\n else {\n if (temp.left != null) {\n path.push(temp.left);\n sub.push(temp.left.val + tempVal);\n }\n if (temp.right != null) {\n path.push(temp.right);\n sub.push(temp.right.val + tempVal);\n }\n }\n }\n return false;\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 7.0MB*** (beats 100.00% / 100.00%).\n* ***C++***\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int sum) {\n if(!root)return false; //Terminating Condition\n sum=sum-root->val; //Body\n if(sum==0&&!root->left&&!root->right)return true; //body\n return hasPathSum(root->left,sum)||hasPathSum(root->right,sum);//Propagation\n }\n};\n```\n\n```\n```\n\n```\n```\n\n\nThe best result for the code below is ***26ms / 12.2MB*** (beats 95.42% / 82.32%).\n* ***Python***\n```\ndef hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n\n def inorder(root, path_sum):\n if not root:\n return False\n \n path_sum+=root.val\n \n if not root.left and not root.right:\n return path_sum==targetSum\n \n return inorder(root.left, path_sum) or inorder(root.right, path_sum)\n \n return inorder(root, 0)\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***51ms / 34.2MB*** (beats 100.00% / 84.12%).\n* ***JavaScript***\n```\nvar hasPathSum = function(root, targetSum) {\n return dfs(root, targetSum);\n // T.C: O(N)\n // S.C: O(H)\n};\n\nconst dfs = (root, target) => {\n if (!root) {\n return false;\n }\n if (!root.left && !root.right) {\n return target - root.val === 0;\n }\n return dfs(root.left, target - root.val) || \n dfs(root.right, target - root.val);\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***68ms / 44.2MB*** (beats 100.00% / 45.25%).\n* ***Kotlin***\n```\nclass Solution {\n fun hasPathSum(root: TreeNode?, sum: Int): Boolean {\n if (root==null){\n return false\n }\n else if (root.left==null && root.right==null && root!!.`val`==sum){\n return true\n }\n return hasPathSum(root.left, sum-root!!.`val`) || hasPathSum(root.right, sum-root!!.`val`)\n }\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***12ms / 32.2MB*** (beats 95% / 84%).\n* ***Swift***\n```\nclass Solution {\n func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool {\n guard let root = root else {\n return false\n }\n \n if root.left == nil && root.right == nil {\n return root.val == targetSum\n }\n \n return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)\n }\n}\n```\n\n```\n```\n\n```\n```\n\n***"Open your eyes. Expect us." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC***\n | 7 | 0 | ['Recursion', 'Swift', 'C', 'PHP', 'Python', 'Java', 'Kotlin', 'JavaScript'] | 2 |
path-sum | [JavaScript] Easy to understand - DFS | javascript-easy-to-understand-dfs-by-pop-kx4r | Since we need to sum the values from root to leaf, it\'s straightforward to think about DFS. So, the process could be:\n1. Traverse the tree via DFS\n2. Check w | poppinlp | NORMAL | 2021-11-09T02:11:42.483945+00:00 | 2021-11-09T02:11:42.483979+00:00 | 573 | false | Since we need to sum the values from root to leaf, it\'s straightforward to think about DFS. So, the process could be:\n1. Traverse the tree via DFS\n2. Check whether current node is leaf\n\t- check the target value\n\t- continue recursion\n\nHere\'s the code:\n\n```js\nconst hasPathSum = (node, target) => {\n if (!node) return false;\n if (!node.left && !node.right) return target === node.val;\n return (\n hasPathSum(node.left, target - node.val) ||\n hasPathSum(node.right, target - node.val)\n );\n};\n```\n\nEven, we could make it in 1-line:\n\n```js\nconst hasPathSum = (node, target) => !!node && (!node.left && !node.right ? target === node.val : hasPathSum(node.left, target - node.val) || hasPathSum(node.right, target - node.val));\n``` | 7 | 0 | ['JavaScript'] | 0 |
path-sum | Two Approaches, DFS, Very simple, C++ | two-approaches-dfs-very-simple-c-by-akas-tir8 | \nImplementation\n\n1st Approach using helper(findPath) method\nTime Complexity = O(N), Space Complexity = O(H) where H is the height of the Binary Tree\n\n\ncl | akashsahuji | NORMAL | 2021-10-12T14:07:42.544506+00:00 | 2021-10-25T01:43:47.767677+00:00 | 507 | false | \nImplementation\n\n**1st Approach using helper(findPath) method\nTime Complexity = O(N), Space Complexity = O(H) where H is the height of the Binary Tree**\n\n```\nclass Solution {\npublic:\n bool findPath(TreeNode* root, int targetSum, int sum){\n if(root == NULL) return false;\n sum += root->val;\n \n if(root->left == NULL && root->right == NULL){\n return (sum == targetSum) ? true : false;\n }\n return (findPath(root->left, targetSum, sum) || findPath(root->right, targetSum, sum)); \n }\n \n bool hasPathSum(TreeNode* root, int targetSum) { \n return findPath(root, targetSum, 0);\n }\n};\n```\n\n**2nd Approach without using any helper method\nTime Complexity = O(N), Space Complexity = O(H) where H is the height of the Binary Tree**\n\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) { \n if(root == NULL) return false;\n targetSum -= root->val;\n \n if(root->left == NULL && root->right == NULL){\n return (targetSum == 0) ? true : false;\n }\n return (hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum)); \n }\n};\n```\n\nIf you find any issue in understanding the solution then comment below, will try to help you.\nIf you found my solution useful.\nSo **please do upvote and encourage me** to document all leetcode problems\uD83D\uDE03\nHappy Coding **:)** | 7 | 0 | ['Depth-First Search', 'Recursion', 'C', 'Binary Tree'] | 4 |
path-sum | JAVA [DFS] : Runtime: 0 ms, faster than 100.00% & Memory Usage: 39.2 MB, less than 73.39% | java-dfs-runtime-0-ms-faster-than-10000-d2fad | \n// Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.\n// Memory Usage: 39.2 MB, less than 73.39% of Java online submissions for Path | sdemirel | NORMAL | 2020-07-20T18:26:37.105155+00:00 | 2020-07-20T18:26:37.105183+00:00 | 602 | false | ```\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.\n// Memory Usage: 39.2 MB, less than 73.39% of Java online submissions for Path Sum.\nclass Solution {\n private boolean answer = false;\n public boolean hasPathSum(TreeNode root, int sum) {\n if(root==null) return false;\n dfs(root,sum,0);\n return answer; \n }\n \n private void dfs(TreeNode node, int sum, int currentSum){\n if(answer==true) return;\n \n if(node.left==null && node.right==null){\n currentSum+=node.val;\n if(sum==currentSum) answer = true;\n return;\n }\n \n currentSum+=node.val;\n if(node.left!=null) dfs(node.left, sum, currentSum);\n if(node.right!=null) dfs(node.right,sum,currentSum);\n }\n}\n``` | 7 | 0 | ['Depth-First Search', 'Java'] | 1 |
path-sum | Java - 0ms - Recursive | java-0ms-recursive-by-horizonhhh-38pt | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) | horizonhhh | NORMAL | 2020-02-23T01:28:55.115778+00:00 | 2020-02-23T01:28:55.115831+00:00 | 679 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n if(root == null)\n return false;\n else\n return (root.left == null && root.right == null && root.val == sum)\n || hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n }\n}\n``` | 7 | 0 | ['Recursion', 'Java'] | 0 |
path-sum | My solution in C++ | my-solution-in-c-by-murdem91-6rjo | /**\n * Definition for binary tree\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeN | murdem91 | NORMAL | 2015-01-04T21:54:52+00:00 | 2015-01-04T21:54:52+00:00 | 1,568 | false | /**\n * Definition for binary tree\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n class Solution {\n public:\n bool hasPathSum(TreeNode *root, int sum) {\n if(!root) return false;\n if(!root->left && !root->right)\n return root->val == sum;\n return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val);\n }\n }; | 7 | 0 | [] | 0 |
path-sum | My Java Solution | my-java-solution-by-hsle-wxq8 | public class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null)\n return false;\n | hsle | NORMAL | 2015-03-26T05:42:32+00:00 | 2015-03-26T05:42:32+00:00 | 984 | false | public class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null)\n return false;\n if (root.left == null && root.right == null)\n return sum == root.val;\n return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);\n } \n } | 7 | 0 | [] | 0 |
path-sum | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-95pl | Explanation []\nauthorslog.com/blog/Wj6FZWGWa9\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) \n {\n | Dare2Solve | NORMAL | 2024-07-15T18:10:56.721189+00:00 | 2024-07-15T18:10:56.721222+00:00 | 2,437 | false | ```Explanation []\nauthorslog.com/blog/Wj6FZWGWa9\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) \n {\n if (root == nullptr) {\n return false;\n }\n targetSum -= root->val;\n if (root->left == nullptr && root->right == nullptr) {\n return targetSum == 0;\n }\n return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);\n }\n};\n```\n\n```python []\nclass Solution:\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n if not root:\n return False\n targetSum -= root.val\n if not root.left and not root.right:\n return targetSum == 0\n return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)\n```\n\n```java []\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n targetSum -= root.val;\n if (root.left == null && root.right == null) {\n return targetSum == 0;\n }\n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n }\n}\n```\n\n```javascript []\nvar hasPathSum = function(root, targetSum) \n{\n if (root == null) {\n return false;\n }\n targetSum -= root.val;\n if (root.left == null && root.right == null) \n {\n return targetSum == 0;\n }\n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n};\n``` | 6 | 0 | ['Tree', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
path-sum | ✅ C++ | Easy in 3 lines | c-easy-in-3-lines-by-kosant-pfgl | Code\n\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if (!root) return false;\n if (root->val == targetSum && | kosant | NORMAL | 2023-05-15T07:10:06.146369+00:00 | 2023-05-15T07:10:06.146399+00:00 | 3,781 | false | # Code\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if (!root) return false;\n if (root->val == targetSum && !root->left && !root->right) return true;\n return hasPathSum(root->right, targetSum - root->val) || hasPathSum(root->left, targetSum - root->val);\n }\n};\n\n``` | 6 | 0 | ['Tree', 'C', 'Binary Tree', 'C++'] | 1 |
path-sum | Easiest Java Solution || Beats 100% || Recursive | easiest-java-solution-beats-100-recursiv-y2ar | Intuition\nIteration of Tree and summing up the path till leaf.\nsearcing the leaf node is equal to target or not.\n\n# Approach\njust like node to leaf sum pro | harshverma2702 | NORMAL | 2023-04-15T05:42:52.959560+00:00 | 2023-04-15T05:42:52.959602+00:00 | 3,488 | false | # Intuition\nIteration of Tree and summing up the path till leaf.\nsearcing the leaf node is equal to target or not.\n\n# Approach\njust like node to leaf sum problem , sum up all path till leaf\nex- \n```\ntree = 1 and target is 11\n / \\\n 2 3\n / / \\\n 5 4 7\n```\n\nso after path() function tree will be like\n```\n 1\n / \\\n 3 4\n / / \\\n 8 8 11 \n\n```\n* now search through the leaf to check is there any targetSum present or not if any return true else false \n\n# Complexity\n- Time complexity:\nO(N)\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n public boolean hasPathSum(TreeNode root, int targetSum){\n path(root);\n return has(root,targetSum);\n }\n public boolean has(TreeNode root, int targetSum) {\n if(root==null)\n return false;\n\n if(root.left==null && root.right==null){\n if(root.val==targetSum)\n return true;\n }\n\n return has(root.left,targetSum) || has(root.right,targetSum);\n }\n\n public static void path(TreeNode root){\n if(root==null)\n return;\n int data = root.val;\n if(root.left!=null)\n root.left.val += data;\n\n if(root.right!=null)\n root.right.val += data;\n\n path(root.left);\n path(root.right);\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
path-sum | My shortest C++ solution | my-shortest-c-solution-by-bishal_722-2sav | \n# Code\nC++ []\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if (!root)\n return false;\n \n | bishal_722 | NORMAL | 2023-03-14T03:12:29.548340+00:00 | 2023-11-05T05:06:33.479436+00:00 | 1,694 | false | \n# Code\n```C++ []\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if (!root)\n return false;\n \n if (root->val == targetSum and !root->left and !root->right)\n return true;\n \n return hasPathSum(root->left, targetSum - root->val) or hasPathSum(root->right, targetSum - root->val);\n }\n};\n```\n\n# Complexity\n- Time Complexity : $$O(n)$$ [worst case : Traverse all `n` nodes]\n- Space Complexity : $$O(1)$$ Extra space (except recursion stack) | 6 | 0 | ['C++'] | 1 |
path-sum | ✅ Cleanest TypeScript Solution (DFS) | cleanest-typescript-solution-dfs-by-mlaj-j9ef | Code (DFS)\n\nfunction hasPathSum(root: TreeNode | null, targetSum: number): boolean {\n if (!root) return false\n if (!root.left && !root.right && root.v | mlajkim | NORMAL | 2023-02-12T20:27:26.207584+00:00 | 2023-02-12T20:27:26.207627+00:00 | 587 | false | # Code (DFS)\n```\nfunction hasPathSum(root: TreeNode | null, targetSum: number): boolean {\n if (!root) return false\n if (!root.left && !root.right && root.val === targetSum) return true\n\n return hasPathSum(root.left, targetSum - root.val)\n || hasPathSum(root.right, targetSum - root.val)\n};\n``` | 6 | 0 | ['TypeScript'] | 1 |
path-sum | JAVASCRIPT SIMPLE || Up vote if u like | javascript-simple-up-vote-if-u-like-by-v-gktr | Code\n\nvar hasPathSum = function(root, targetSum) {\n if (!root) return false // not a leaf\n if (!root.left && !root.right) return root.val === targetSu | vfyodorov | NORMAL | 2023-01-16T09:01:23.290848+00:00 | 2023-01-16T09:01:23.290894+00:00 | 852 | false | # Code\n```\nvar hasPathSum = function(root, targetSum) {\n if (!root) return false // not a leaf\n if (!root.left && !root.right) return root.val === targetSum; // leaf\n\n return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);\n};\n``` | 6 | 0 | ['JavaScript'] | 0 |
path-sum | 0ms JAVA SOLUTION ANOTHER APPROACH | 0ms-java-solution-another-approach-by-ma-plpd | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n | Maheshwari_Saksham | NORMAL | 2023-01-12T09:22:41.071767+00:00 | 2023-01-12T09:22:41.071814+00:00 | 1,205 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean hasPathSum(TreeNode root, int target) \n {\n if(root==null)\n return false;\n if(root.left==null && root.right==null)\n return (target-root.val)==0;\n return hasPathSum(root.left,target-root.val) || hasPathSum(root.right,target-root.val); \n }\n}\n``` | 6 | 0 | ['Tree', 'Java'] | 0 |
path-sum | Python || recursive | python-recursive-by-georgeofgeorgia-kj0o | \nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n def helper(node,tot):\n if not node:\n | georgeofgeorgia | NORMAL | 2022-11-14T08:11:44.723926+00:00 | 2022-11-14T08:11:44.723963+00:00 | 629 | false | ```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n def helper(node,tot):\n if not node:\n return \n elif not node.left and not node.right:\n if tot+node.val==targetSum:\n return True\n else:\n return helper(node.left,tot+node.val) or helper(node.right,tot+node.val)\n if root:\n return helper(root,0)\n``` | 6 | 0 | [] | 1 |
path-sum | C++ || Concise recursion || Clean Inorder traversal | c-concise-recursion-clean-inorder-traver-wo78 | \n bool inorder(TreeNode* root , int sum , int &targetSum)\n {\n if(!root) return false;\n sum+=root->val;\n if(root->left==NULL && roo | ashay028 | NORMAL | 2022-10-04T17:26:05.359325+00:00 | 2022-10-04T17:26:05.359363+00:00 | 216 | false | ```\n bool inorder(TreeNode* root , int sum , int &targetSum)\n {\n if(!root) return false;\n sum+=root->val;\n if(root->left==NULL && root->right==NULL) if(sum==targetSum) return true; \n return (inorder(root->left , sum , targetSum) || inorder(root->right , sum , targetSum));\n }\n bool hasPathSum(TreeNode* root, int targetSum) {\n return inorder(root, 0 , targetSum);\n }\n``` | 6 | 0 | [] | 0 |
path-sum | Java(0ms) || Simple explanation with TC & SC || Easy to understand | java0ms-simple-explanation-with-tc-sc-ea-rkuo | ```\nclass Solution {\n \n public boolean hasPathSum(TreeNode root, int targetSum) {\n \n //return false when root is null or when we reache | Shaikh_Ovais | NORMAL | 2022-07-03T08:59:20.487936+00:00 | 2022-07-03T10:26:27.446622+00:00 | 257 | false | ```\nclass Solution {\n \n public boolean hasPathSum(TreeNode root, int targetSum) {\n \n //return false when root is null or when we reached leaf node but the sum is not equal to target sum\n if(root == null) {\n return false;\n }\n \n //if the current node is not null then we subract targetSum by it\'s value and pass the new targetSum ahead in the function\n targetSum = targetSum - root.val;\n \n //if both sides are null then it means that we have reached leaf node and if at the same time targetSum is also equals to 0 then we can return true because we have found the path\n if(root.left == null && root.right == null && 0 == targetSum) {\n return true;\n }\n \n //we do a recursive call for both the sides and use \'or(||)\' function because even if one side is true then we got the ans(path)\n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n }\n \n}\n\n//Time Complexity: O(n) n is the total number of nodes in the binary tree\n//Space Complexity: O(n) n is the total number of nodes in the binary tree\n//Please upvote the solution if you like it | 6 | 0 | ['Recursion', 'Java'] | 0 |
path-sum | 90 % Faster C++ Solution | 90-faster-c-solution-by-ariyanlaskar-kack | \n bool hasPathSum(TreeNode* root, int targetSum) {\n if(!root){\n return false;\n }\n if(targetSum==root->val && root->left==NU | Ariyanlaskar | NORMAL | 2021-10-31T11:13:43.457057+00:00 | 2021-10-31T11:13:43.457098+00:00 | 402 | false | ```\n bool hasPathSum(TreeNode* root, int targetSum) {\n if(!root){\n return false;\n }\n if(targetSum==root->val && root->left==NULL && root->right==NULL){\n return true;\n }\n return hasPathSum(root->left,targetSum-(root->val)) || hasPathSum(root->right,targetSum-(root->val));\n }\n```\nFor More LeetCode Problem\'s Solution(Topic-Wise)Please Check Out;\nhttps://github.com/Ariyanlaskar/DSA/tree/master/LeetCode | 6 | 0 | ['C'] | 0 |
path-sum | C# DFS Recursive, DFS Iterative and BFS | c-dfs-recursive-dfs-iterative-and-bfs-by-lqy4 | DFS Recursive:\n\n\npublic bool HasPathSum(TreeNode root, int targetSum)\n{\n if(root == null)\n return false;\n \n if(root.left == null && root | akmetainfo | NORMAL | 2021-08-03T21:47:51.885488+00:00 | 2021-08-03T22:05:40.691937+00:00 | 324 | false | DFS Recursive:\n\n```\npublic bool HasPathSum(TreeNode root, int targetSum)\n{\n if(root == null)\n return false;\n \n if(root.left == null && root.right == null)\n return root.val == targetSum;\n \n return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);\n}\n```\n\nDFS Iterative:\n\n```\npublic bool HasPathSum(TreeNode root, int targetSum)\n{\n if(root == null)\n return false;\n \n var stack = new Stack<TreeNode>();\n var rest = new Stack<int>();\n \n stack.Push(root);\n rest.Push(targetSum);\n \n while(stack.Count() > 0)\n {\n root = stack.Pop();\n targetSum = rest.Pop();\n \n if(root.left == null && root.right == null)\n {\n if(targetSum == root.val)\n return true;\n }\n \n if(root.left != null)\n {\n stack.Push(root.left);\n rest.Push(targetSum - root.val);\n }\n \n if(root.right != null)\n {\n stack.Push(root.right);\n rest.Push(targetSum - root.val);\n }\n }\n return false;\n}\n```\n\nBFS:\n\n```\npublic bool HasPathSum(TreeNode root, int targetSum)\n{\n if (root == null)\n return false;\n \n var queue = new Queue<TreeNode>();\n var rest = new Queue<int>();\n \n queue.Enqueue(root);\n rest.Enqueue(targetSum);\n\n while (queue.Count() > 0)\n {\n root = queue.Dequeue();\n targetSum = rest.Dequeue();\n \n if (root.left == null && root.right == null)\n {\n if(targetSum == root.val)\n return true;\n }\n \n if(root.left != null)\n {\n queue.Enqueue(root.left);\n rest.Enqueue(targetSum - root.val);\n }\n \n if(root.right != null)\n {\n queue.Enqueue(root.right);\n rest.Enqueue(targetSum - root.val);\n }\n }\n\n return false;\n}\n``` | 6 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Recursion', 'Iterator'] | 0 |
path-sum | Simple recursive Python 3 | simple-recursive-python-3-by-gecko50-735c | Algorithm:\n decrement the sum as you recurse down the binary tree\n if you are at a leaf node, check if sum == 0\n\n\nclass Solution:\n def hasPathSum(self, | gecko50 | NORMAL | 2020-10-15T22:42:42.982024+00:00 | 2020-10-15T22:42:42.982069+00:00 | 963 | false | Algorithm:\n* decrement the sum as you recurse down the binary tree\n* if you are at a leaf node, check if `sum == 0`\n\n```\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n\n sum -= root.val\n \n #only check sum if it is a leaf node\n if root.left == None and root.right == None:\n if sum == 0:\n return True\n return False\n\n return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)\n``` | 6 | 1 | ['Depth-First Search', 'Python', 'Python3'] | 1 |
snakes-and-ladders | C++ || Simple BFS (With Full Explanation)🌚 || Beats 100% 🏁🔥 | c-simple-bfs-with-full-explanation-beats-84jo | Intuition\nThe intuition behind this code is that it uses a breadth-first search (BFS) algorithm to find the minimum number of moves required to reach the last | ufoblivr | NORMAL | 2023-01-24T01:48:13.505668+00:00 | 2023-01-24T15:03:59.589930+00:00 | 38,660 | false | # Intuition\nThe intuition behind this code is that it uses a breadth-first search (BFS) algorithm to find the minimum number of moves required to reach the last cell of the board from the first cell. BFS is an algorithm that explores all the vertices of a graph or all the nodes of a tree level by level.\n\n# Approach\nThe method starts by creating a vector of pairs called **"cells"** that stores the row and column of each cell in the board. It also creates a vector of integers called **"dist"** that stores the minimum number of moves required to reach each cell and initializes it to -1.\n\nIt then uses a queue to keep track of the cells to be visited and starts by pushing the first cell (cell 1) into the queue. The method then enters a while loop that continues until the queue is empty. In each iteration of the loop, it takes the front element of the queue, which is the current cell, and pops it from the queue.\n\nFor the current cell, the method loops through all the possible next cells which are from curr+1 to min(curr+6,n*n) (because in each move we can move to a dice roll max 6 steps) and checks if the minimum number of moves required to reach that cell has not been assigned yet. If it has not been assigned yet, the method assigns the minimum number of moves required to reach that cell as the minimum number of moves required to reach the current cell plus one. It also pushes the next cell into the queue to be visited in the next iteration.\n\nThe method then continues this process until all the cells have been visited, and the minimum number of moves required to reach each cell has been assigned. Finally, the method returns the minimum number of moves required to reach the last cell, which is stored in dist[n*n].\n\nIt also handles the case if there is a snake or ladder at the cell, it directly assigns the destination cell number as the cell number.\n\n# Complexity\n- **Time complexity:**\nThe time complexity of this code is **O(n^2)**, where n is the size of the board. This is because the method uses a breadth-first search algorithm to traverse through each cell of the board and assigns the distance of each cell from the starting cell. The outer loop iterates n times, and the inner loop iterates n times, so the total number of iterations is n*n.\nNote that this is assuming the queue and vector operations have a constant time complexity, which is typical but not guaranteed.\n\n- **Space complexity:**\nThe space complexity of this code is also **O(n^2)**. This is because the method uses a vector of integers called "dist" to keep track of the minimum number of moves required to reach each cell, and this vector has nn elements. The method also uses a vector of pairs called "cells" to keep track of the row and column of each cell, and this vector also has nn elements. The method also uses a queue to keep track of the cells to be visited, which can have at most n*n elements.\n\n\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>> &board) {\n int n = board.size(), lbl = 1;\n vector<pair<int, int>> cells(n*n+1);\n vector<int> columns(n);\n iota(columns.begin(), columns.end(), 0);\n for (int row = n - 1; row >= 0; row--) {\n for (int column : columns) {\n cells[lbl++] = {row, column};\n }\n reverse(columns.begin(), columns.end());\n }\n vector<int> dist(n*n+1, -1);\n dist[1] = 0;\n queue<int> q;\n q.push(1);\n while (!q.empty()) {\n int curr = q.front();\n q.pop();\n for (int next = curr + 1; next <= min(curr+6, n*n); next++) {\n auto [row, column] = cells[next];\n int destination = board[row][column] != -1 ? board[row][column] : next;\n if (dist[destination] == -1) {\n dist[destination] = dist[curr] + 1;\n q.push(destination);\n }\n }\n }\n return dist[n*n];\n }\n};\n```\n\n\n\n | 777 | 5 | ['Breadth-First Search', 'C++'] | 10 |
snakes-and-ladders | Diagram and BFS | diagram-and-bfs-by-lee215-xhwv | I drew this diagram.\nHope it help understand the problem.\n(shouldn\'t leetcode note the author?)\n\n\n\nPython:\n\n def snakesAndLadders(self, board):\n | lee215 | NORMAL | 2018-09-23T03:05:22.656545+00:00 | 2020-09-02T14:58:59.438230+00:00 | 55,913 | false | **I drew this diagram.**\nHope it help understand the problem.\n(shouldn\'t leetcode note the author?)\n\n<img alt="" src="https://assets.leetcode.com/users/lee215/image_1537671763.png" style="width: 500px;" />\n\n**Python:**\n```\n def snakesAndLadders(self, board):\n n = len(board)\n need = {1: 0}\n bfs = [1]\n for x in bfs:\n for i in range(x + 1, x + 7):\n a, b = (i - 1) / n, (i - 1) % n\n nxt = board[~a][b if a % 2 == 0 else ~b]\n if nxt > 0: i = nxt\n if i == n * n: return need[x] + 1\n if i not in need:\n need[i] = need[x] + 1\n bfs.append(i)\n return -1\n```\n | 612 | 22 | [] | 58 |
snakes-and-ladders | Change to 1D array then BFS | change-to-1d-array-then-bfs-by-wangzi614-g6on | \nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int[] arr = new int[n * n];\n int i = n - 1, | wangzi6147 | NORMAL | 2018-09-23T03:15:12.185327+00:00 | 2018-10-26T05:52:31.097447+00:00 | 31,830 | false | ```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int[] arr = new int[n * n];\n int i = n - 1, j = 0, index = 0, inc = 1;\n while (index < n * n) {\n arr[index++] = board[i][j];\n if (inc == 1 && j == n - 1) {\n inc = -1;\n i--;\n } else if (inc == -1 && j == 0) {\n inc = 1;\n i--;\n } else {\n j += inc;\n }\n }\n boolean[] visited = new boolean[n * n];\n Queue<Integer> q = new LinkedList<>();\n int start = arr[0] > -1 ? arr[0] - 1 : 0;\n q.offer(start);\n visited[start] = true;\n int step = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n while (size-- > 0) {\n int cur = q.poll();\n if (cur == n * n - 1) {\n return step;\n }\n for (int next = cur + 1; next <= Math.min(cur + 6, n * n - 1); next++) {\n int dest = arr[next] > -1 ? arr[next] - 1 : next;\n if (!visited[dest]) {\n visited[dest] = true;\n q.offer(dest);\n }\n }\n }\n step++;\n }\n return -1;\n }\n}\n``` | 195 | 2 | [] | 40 |
snakes-and-ladders | Java concise solution easy to understand | java-concise-solution-easy-to-understand-1f6a | \n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<Integer> queue = new LinkedList<>();\n queue.offer(1);\n | yuxiangmusic | NORMAL | 2018-09-23T20:18:24.673709+00:00 | 2018-10-16T02:23:01.157291+00:00 | 18,274 | false | ```\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<Integer> queue = new LinkedList<>();\n queue.offer(1);\n boolean[] visited = new boolean[n * n + 1];\n for (int move = 0; !queue.isEmpty(); move++) {\n for (int size = queue.size(); size > 0; size--) {\n int num = queue.poll();\n if (visited[num]) continue;\n visited[num] = true;\n if (num == n * n) return move;\n for (int i = 1; i <= 6 && num + i <= n * n; i++) {\n int next = num + i;\n int value = getBoardValue(board, next);\n if (value > 0) next = value;\n if (!visited[next]) queue.offer(next);\n }\n }\n }\n return -1;\n }\n\n private int getBoardValue(int[][] board, int num) {\n int n = board.length;\n int r = (num - 1) / n;\n int x = n - 1 - r;\n int y = r % 2 == 0 ? num - 1 - r * n : n + r * n - num;\n return board[x][y];\n }\n``` | 120 | 2 | [] | 17 |
snakes-and-ladders | BFS, intuition, diagrams and tests, c++, 12ms | bfs-intuition-diagrams-and-tests-c-12ms-9hd37 | Intuition: \nFor each step we do the follwoing:\n1. roll a dice (and check all 6 possible values, marking each as visited)\n2. check if we land on a ladder and | savvadia | NORMAL | 2019-10-04T06:28:52.499073+00:00 | 2020-03-10T06:32:28.537616+00:00 | 13,632 | false | Intuition: \nFor each step we do the follwoing:\n1. roll a dice (and check all 6 possible values, marking each as visited)\n2. check if we land on a ladder and take it (no possibility to skip it, we must take it)\n3. remember where to continue next time (add the new position to the queue)\n\nNow let\'s take a look at scenarios:\n\n1. Just step starting from square 1 with a dice where 6 is the best :)\n\n[[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1]]\nAnswer: 3\nSteps: e.g. 7 -> 13 -> 16\n\n2. Take a ladder inside a step. Step over ladders with a "dice" move\n\n[[-1,2,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,14,-1]]\nAnswer: 2\nSteps: [3]14 -> 16\n\n3. We take just one ladder during the move ignoring a ladder which might be waiting on the other end\n\n[[-1,-1,2,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,14,-1]]\nAnswer: 2\nSteps: [3]14 -> 16\n \n 4. Mark a position as visited only on a dice move (not after you took a ladder), because the position is covered only after you have checked a ladder from this position.\nRed arrows show a longer way taking the first ladder, to 8. If we now mark 8 as visited, we would never take a ladder from 8 directly to the target.\n \n[[-1,-1,-1,-1],[-1,-1,-1,-1],[16,-1,8,-1],[-1,-1,-1,-1]]\nAnswer: 2\nSteps: e.g. 5 -> [8]16 \n\nHow can we make it faster?\n* handle new positions with the smallest number of steps first\n* consider how close we are to the target; it\'s better to try first the square closest to the target\n\nIf you are lost in a failing test, store the number of steps to reach the position in the visited array. Then you can print out the number of steps for positions in the correct answer and see where you took the wrong way.\n\n```\ntypedef pair<int,int> Pi;\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int rows=board.size(), cols = board[0].size(), target=rows*cols, r, c, p;\n vector<int> visited(rows*cols + 1); // cells on board start from 1\n\n // queue contains <priority, square> sorted ascending by priority\n // prio = #steps * 1000 + (500 - square);\n // number of steps is critical and adds 1000; 500 is selected as it is higher than the max cell (20*20=400)\n priority_queue<Pi, vector<Pi>, greater<Pi>> q;\n q.push(make_pair(0,1)); // 0 steps to position 1\n visited[1] = true;\n\n while(q.size())\n {\n auto step_pos = q.top(); q.pop();\n int s = step_pos.first/1000 + 1;\n \n for(int i=1; i<=6; i++)\n {\n auto p = step_pos.second+i;\n if(visited[p]) continue;\n visited[p] = true;\n \n r = rows - (p-1) / cols - 1;\n c = (p-1) % cols;\n if((rows-r-1)%2) c = cols - c - 1; // change direction for odd lines\n int ladder = board[r][c];\n if(ladder>0 && ladder<=target)\n p = ladder; // no update for steps. allow to come here again with a dice\n \n if(p == target) return s;\n q.push(make_pair(s*1000+500-p, p));\n }\n }\n return -1;\n }\n};\n```\n\nYou can print the board and the ladders with the code:\n```\n for(auto& v : board)\n {\n for(int i : v) cout <<i<<" ";\n cout<<endl;\n } \n cout <<"---"<<endl;\n for(int i=rows-1;i>=0;i--)\n {\n if(i%2==0)\n for(int j=0;j<cols;j++)\n cout << i*cols + j + 1<<" ";\n else\n for(int j=cols-1;j>=0;j--)\n cout << i*cols + j + 1<<" ";\n cout <<endl;\n }\n```\n\nAnswers for the tricky tests:\n1. [[-1,1,2,-1],[2,13,15,-1],[-1,10,-1,-1],[-1,6,2,8]]\n\n1 -> 7 [ladder to 10] -> 16, two moves in total\n```\n-1 1 2 -1 \n 2 13 15 -1 \n-1 10 -1 -1 \n-1 6 2 8 \n---\n16 15 14 13 \n 9 10 11 12 \n 8 7 6 5 \n 1 2 3 4 \n```\n\n2. [[-1,-1,19,10,-1],[2,-1,-1,6,-1],[-1,17,-1,19,-1],[25,-1,20,-1,-1],[-1,-1,-1,-1,15]]\nAnswer: 1->4->10[25] or 1->6->10[25], two steps\n```\n-1 -1 19 10 -1 \n 2 -1 -1 6 -1 \n-1 17 -1 19 -1 \n25 -1 20 -1 -1 \n-1 -1 -1 -1 15 \n---\n21 22 23 24 25 \n20 19 18 17 16 \n11 12 13 14 15 \n10 9 8 7 6 \n 1 2 3 4 5 \n```\n\n3. [[-1,-1,30,14,15,-1],[23,9,-1,-1,-1,9],[12,5,7,24,-1,30],[10,-1,-1,-1,25,17],[32,-1,28,-1,-1,32],[-1,-1,23,-1,13,19]]\nAnswer: 1->7[32]->36, two steps\n```\n-1 -1 30 14 15 -1 \n23 9 -1 -1 -1 9 \n12 5 7 24 -1 30 \n10 -1 -1 -1 25 17 \n32 -1 28 -1 -1 32 \n-1 -1 23 -1 13 19 \n---\n36 35 34 33 32 31 \n25 26 27 28 29 30 \n24 23 22 21 20 19 \n13 14 15 16 17 18 \n12 11 10 9 8 7 \n 1 2 3 4 5 6 \n``` | 106 | 1 | ['Breadth-First Search', 'C'] | 9 |
snakes-and-ladders | Python3 clear BFS solution | python3-clear-bfs-solution-by-jinjiren-4fk1 | Thought process\n- simply apply BFS to find the length of shortest path from 1 to n*n\n- key point is to correctly compute the corresponding coordinates of the | jinjiren | NORMAL | 2019-06-18T04:26:59.148806+00:00 | 2019-06-18T04:26:59.148846+00:00 | 9,256 | false | ## Thought process\n- simply apply BFS to find the length of shortest path from `1` to `n*n`\n- key point is to correctly compute the corresponding coordinates of the label\n- also remember to avoid circle by using a hashset to track visited positions\n- time complexity: O(n^2), n is the width and height of the grid\n- space complexity: O(n^2)\n\n\n```py\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n def label_to_position(label):\n r, c = divmod(label-1, n)\n if r % 2 == 0:\n return n-1-r, c\n else:\n return n-1-r, n-1-c\n \n seen = set()\n queue = collections.deque()\n queue.append((1, 0))\n while queue:\n label, step = queue.popleft()\n r, c = label_to_position(label)\n if board[r][c] != -1:\n label = board[r][c]\n if label == n*n:\n return step\n for x in range(1, 7):\n new_label = label + x\n if new_label <= n*n and new_label not in seen:\n seen.add(new_label)\n queue.append((new_label, step+1))\n return -1\n``` | 101 | 1 | ['Breadth-First Search', 'Python'] | 11 |
snakes-and-ladders | C++: bfs || detailed explanation || faster than 99.31% | c-bfs-detailed-explanation-faster-than-9-x2o9 | Lets assume number of rows and column is n.\nThe trick is to find the coornidate of the square with number s. If you can find the coordinate of given square wit | bingabid | NORMAL | 2020-08-16T08:40:32.376077+00:00 | 2021-12-25T09:08:40.215142+00:00 | 8,170 | false | Lets assume number of rows and column is n.\nThe trick is to find the coornidate of the square with number s. If you can find the coordinate of given square with number s then it\'s just a plain vanilla bfs. Since rows are starting from bottom, just dividing \'s\' by \'n\' won\'t work. So, to get actual rows from bottom, we need to subtract it from \'n-1\' (-1 because of \'0\' based indexing). Hence,\n\n```\nrow_from_top = (s-1)/n; \nrow_from_bottom = n-1-row_from_top\n\t\t\t\t= n-1-(s-1)/n;\n(s-1) because of \'0\' based indexing and take care of corner cases when s%n == 0; to understand it better, please dry run following case. \ne.g n=6, s= 24\n\trow_from_top = (24-1)/6 = 3\n\trow_from_bottom = 6-1-3 = 2;\n\t\n\tn=6,s=18\n\trow_from_top = (18-1)/6 = 2\n\trow_from_bottom = 6-1-2 = 3;\n\t\n\tn=5,s=17\n\trow_from_top = (17-1)/5 = 3\n\trow_from_bottom = 5-1-3 = 1;\n\t\n```\n\t\nGetting column is bit tricky here because of boustrophedonically ordering. \nIn normal ordering: col = (s-1)%n \nBut because of boustrophedonically ordering, the column number alternets from left to right and from right to left. If you observe carefully \nwhen (n and row_from_bottom are even) or (n and row_from_bottom are odd), the column number starts from right to left; Hence, to get actual column number we need to subtract it from n-1. i.e \n\n```\ncol = (s-1)%n;\nif((n%2==0 && row_from_bottom%2==0)||(n%2==1 && row_from_bottom%2==1))\n\tcol = n-1-col;\ne.g n=6,s=24\n\tcol = (24-1)%6 = 5\n\trow_from_top = (24-1)/6 = 3\n\trow_from_bottom = 6-1-3 = 2;\n\tsince, n & row_from_bottom both are even, \n\tcol = 6-1-col\n\t\t= 0\n\t\t\n\tn=6,s=18\n\trow_from_top = (18-1)/6 = 2\n\trow_from_bottom = 6-1-2 = 3;\n\tcol = (18-1)%6 = 5;\n\t\n\tn=5,s=17\n\trow_from_top = (17-1)/5 = 3\n\trow_from_bottom, = 5-1-3 = 1;\n\tcol = (17-1)%5 = 1\n\tsince n & row_from_bottom are odd, \n\tcol = n-1-col\n\t\t= 5-1-1\n\t\t= 3\n```\n\t\t\nOnce you get the row and col, it\'s straigt forwad bfs starting from 1. maintain an seen vector and do bfs traversal using queue. Below is my implementation in C++\n\n```\nclass Solution {\n void getCoordinate(int n,int s, int &row, int &col){\n row = n-1-(s-1)/n;\n col = (s-1)%n;\n if((n%2==1 && row%2==1)||(n%2==0 && row%2==0))\n col = n-1-col;\n }\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<bool> seen(n*n+1,false);\n\t\tseen[1] = true;\n queue<pair<int,int>> q;\n\t\tq.push({1,0});\n while(!q.empty()){\n pair<int,int> p = q.front();q.pop();\n int row,col,s = p.first, dist = p.second;\n if(s == n*n)\n return dist;\n for(int i=1;s+i<=n*n && i<=6;i++){ \n getCoordinate(n,s+i,row,col);\n int sfinal = board[row][col]==-1?s+i:board[row][col]; // check for snake or ladder\n if(seen[sfinal]==false){\n seen[sfinal] = true;\n q.push({sfinal,dist+1});\n } \n }\n }\n return -1;\n }\n};\n``` | 94 | 0 | [] | 14 |
snakes-and-ladders | Day 24 || Easiest Beginner Friendly Solution || O(n^2) time and O(n^2) space | day-24-easiest-beginner-friendly-solutio-e5kp | Intuition\nThis problem contains simple BFS but the main intution of this problem to find cordinates of particular value i.e. row and column.\n1. the variable " | singhabhinash | NORMAL | 2023-01-24T02:54:46.655093+00:00 | 2023-01-24T05:08:00.840981+00:00 | 9,439 | false | # Intuition\nThis problem contains simple BFS but the main intution of this problem to find cordinates of particular value i.e. row and column.\n1. the variable "row" is calculated by subtracting the quotient of (curr-1) / n from n-1. This is done to convert the 1-indexed position of the element to a 0-indexed position in the board.\n2. the variable "col" is calculated by taking the remainder of (curr-1) % n. This gives the column position of the element on the board.\n3. After that, the code checks if the row number is even or odd. If it is even, it returns a vector containing the row and the value of n-1-col (which is the inverted column position)\nOtherwise, it returns a vector containing the row and the col.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n1. Initialize the variables n as the size of the board, moves as 0, a queue q and a 2D boolean array visited with all elements as false.\n2. Push the value 1 into the queue and mark the element at the last row and first column of the visited array as true.\n3. Start a while loop until the queue is not empty.\n4. In each iteration, set the size of the queue to a variable size.\n5. Run a for loop for i from 0 to size\n6. Dequeue the front element of the queue and store it in a variable currBoardVal\n7. If currBoardVal is equal to n*n, return the value of moves.\n8. Run a for loop for diceVal from 1 to 6.\n9. If currBoardVal + diceVal is greater than n*n, break the loop.\n10. Find the coordinates of the element at position currBoardVal + diceVal in the board by calling the findCoordinates function and store it in a vector pos.\n11. Set row as the first element of the vector pos and col as the second element of the vector pos.\n12. If the element at position row and col in the visited array is false, mark it as true.\n13. If the value at the element at position row and col in the board is -1, push currBoardVal + diceVal into the queue.\n14. Else, push the value at the element at position row and col in the board into the queue.\n15. End the for loop for diceVal.\n16. End the for loop for i.\n17. Increment the value of moves by 1.\n18. End the while loop.\n19. If the while loop ends, return -1 as the final result.\nREFERENCE VIDEO - https://www.youtube.com/watch?v=zWS2fCJGxmU\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n int moves = 0;\n queue<int> q;\n //setting visited array to false initially\n vector<vector<bool>> visited(n, vector<bool>(n, false));\n q.push(1);\n visited[n-1][0] = true;\n while(!q.empty()){\n int size = q.size();\n for(int i = 0; i < size; i++){\n int currBoardVal = q.front();\n q.pop();\n if(currBoardVal == n*n) \n return moves;\n for(int diceVal = 1; diceVal <= 6; diceVal++){\n if(currBoardVal + diceVal > n*n) \n break;\n vector<int> pos = findCoordinates(currBoardVal + diceVal, n);\n int row = pos[0];\n int col = pos[1];\n if(visited[row][col] == false){\n visited[row][col] = true;\n if(board[row][col] == -1){\n q.push(currBoardVal + diceVal);\n }\n else{\n q.push(board[row][col]);\n }\n }\n }\n }\n moves++;\n }\n return -1;\n }\n //Function returns a vector of integers, representing the coordinates (row and column) of the element at position curr on the board.\n vector<int> findCoordinates(int currVal, int n) {\n //calculates the row by subtracting the quotient of (curr-1) / n from n-1. This is done to convert the 1-indexed position of the element to a 0-indexed position in the board.\n int row = n - (currVal - 1) / n - 1;\n int col = (currVal - 1) % n;\n if (row % 2 == n % 2) {\n return {row, n - 1 - col};\n } else {\n return {row, col};\n }\n }\n};\n```\n```Java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int moves = 0;\n Queue<Integer> q = new LinkedList<>();\n boolean[][] visited = new boolean[n][n];\n q.add(1);\n visited[n-1][0] = true;\n while(!q.isEmpty()){\n int size = q.size();\n for(int i = 0; i < size; i++){\n int currBoardVal = q.poll();\n if(currBoardVal == n*n) \n return moves;\n for(int diceVal = 1; diceVal <= 6; diceVal++){\n if(currBoardVal + diceVal > n*n) \n break;\n int[] pos = findCoordinates(currBoardVal + diceVal, n);\n int row = pos[0];\n int col = pos[1];\n if(visited[row][col] == false){\n visited[row][col] = true;\n if(board[row][col] == -1){\n q.add(currBoardVal + diceVal);\n }\n else{\n q.add(board[row][col]);\n }\n }\n }\n }\n moves++;\n }\n return -1;\n }\n public int[] findCoordinates(int curr, int n) {\n int r = n - (curr - 1) / n -1;\n int c = (curr - 1) % n;\n if (r % 2 == n % 2) {\n return new int[]{r, n - 1 - c};\n } else {\n return new int[]{r, c};\n }\n }\n}\n\n```\n```Python []\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n moves = 0\n q = collections.deque([1])\n visited = [[False for _ in range(n)] for _ in range(n)]\n visited[n-1][0] = True\n while q:\n size = len(q)\n for i in range(size):\n currBoardVal = q.popleft()\n if currBoardVal == n*n:\n return moves\n for diceVal in range(1, 7):\n if currBoardVal + diceVal > n*n:\n break\n pos = self.findCoordinates(currBoardVal + diceVal, n)\n row, col = pos\n if not visited[row][col]:\n visited[row][col] = True\n if board[row][col] == -1:\n q.append(currBoardVal + diceVal)\n else:\n q.append(board[row][col])\n moves += 1\n return -1\n \n def findCoordinates(self, curr: int, n: int) -> Tuple[int, int]:\n row = n - (curr - 1) // n - 1\n col = (curr - 1) % n\n if row % 2 == n % 2:\n return (row, n - 1 - col)\n else:\n return (row, col)\n\n```\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** https://www.linkedin.com/in/abhinash-singh-1b851b188\n\n\n# Complexity\n- Time complexity: **O(n^2)**\nThe time complexity of BFS is O(\u2223V\u2223+\u2223E\u2223), where \u2223V\u2223 is the number of vertices and \u2223E\u2223 is the number of edges. We have \u2223V\u2223=n^2 and \u2223E\u2223<6*n^2\n , thus the total time complexity for BFS is O(7n^2)=O(n^2). We also spend some time associating each (row, col) with a label, but this also costs O(n^2), so the overall time complexity is O(n^2).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n^2)** // we are using visited array of size n*n\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 87 | 0 | ['Breadth-First Search', 'Python', 'C++', 'Java'] | 3 |
snakes-and-ladders | ✅Short || C++ || Java || PYTHON || JS || Explained Solution✔️ || Beginner Friendly ||🔥 | short-c-java-python-js-explained-solutio-em3c | Read Fulll Article for code and Explanination...\nhttps://www.nileshblog.tech/leetcode-solving-snakes-and-ladders-with-bfs-algorithm/\n\n\n\n\nRead Both Solutio | amoddeshmukh844 | NORMAL | 2023-01-24T03:43:25.640219+00:00 | 2023-03-10T05:19:30.548232+00:00 | 10,587 | false | Read Fulll Article for code and Explanination...\nhttps://www.nileshblog.tech/leetcode-solving-snakes-and-ladders-with-bfs-algorithm/\n\n\n\n\nRead Both Solution .\n\nSolution 1:BFS**\n**\nTime Complexit o(n^2) space - O(n)\n\n\n | 66 | 10 | ['Python', 'C++', 'Java'] | 1 |
snakes-and-ladders | c++ 💯✅detailed explanation 💥|| easy to understand | c-detailed-explanation-easy-to-understan-wrb9 | note :-----BFS IS BEST FOR FINDING MINIMUM STEPS TO REACH DESTINATION.SO WHENEVER THERE IS GRAPH OR TREE WHERE WE NEED TO CALCULATE MINIMUM STEPS THEN USE BFS\n | sonal91022 | NORMAL | 2023-01-24T11:18:09.972364+00:00 | 2023-05-12T05:42:26.461981+00:00 | 3,199 | false | note :-----**BFS IS BEST FOR FINDING MINIMUM STEPS TO REACH DESTINATION.SO WHENEVER THERE IS GRAPH OR TREE WHERE WE NEED TO CALCULATE MINIMUM STEPS THEN USE BFS**\n\nstep 1) we can go at 6 location from **(5,0)**,please note we started from (5,0) location of the grid .so in bfs qeue insert **board[n-1][0]**.\nstep 2) we insert all 6 locations into qeue from start index .\nstep 3) we have **2,3,4,5,6,7** from 1 we can go to all these cells.\nwe find cordinates of each cell and see if it is -1 or something else. something else means whether ladder or a snake .\n\n\nbelow code is used to calculate cordinates of each cell present in queue when we process it\n\n\nstep 4) we we need to check cell containing -1 then add where is can go **(k+front)** in queue as we are storing values in queue not cordinates .\nif it contins value then we insert it into our queue.\nstep 5) we repeat the same untill queue does not get exhausted.\nwe need to check the elements which need to process is our final destination **(6*6)** .if it is then return no. of bfs called .that will be our answer..\n\nat what condition it will return -1..when we cant reach at 36.\n\n\n\n**time complexity**:- N x N\n**space complexity**:-N x N\n\nLets Connect On Linkedin https://www.linkedin.com/in/sonal-prasad-sahu-78973a229/\n\n# Code\n```\nclass Solution {\npublic: \n vector<int> findcordinates(int pos,int n){\n vector<int>temp;\n int r=n-(pos-1)/n-1;\n int c=(pos-1)%n;\n if(r%2==n%2){\n return temp={r,n-1-c};\n }else{\n return temp={r,c};\n }\n }\n\n\n int snakesAndLadders(vector<vector<int>>& board) {\n int n= board.size();\n queue<int>q;\n vector<vector<bool>>visited( n , vector<bool>(n, false)); \n int ans=0;\n q.push(1);\n visited[n-1][0]=true;\n while(!q.empty()){\n int size=q.size();\n \n for(int i=0;i<size;++i){\n int front=q.front();\n q.pop();\n if(front==n*n) return ans;\n for(int k=1;k<=6;++k){\n if(k+front>n*n) break;\n vector<int>pos=findcordinates(front+k,n);\n int r=pos[0];\n int c=pos[1];\n if(visited[r][c]==true) continue;\n visited[r][c]=true;\n if(board[r][c]!=-1){\n q.push(board[r][c]);\n }else{\n q.push(front+k);\n }\n\n }\n }\n ans++;\n }\n return -1;\n }\n};\n\n```\n\n\n | 52 | 1 | ['C++'] | 3 |
snakes-and-ladders | 🔥Easy Explanation🔥 with Diagram | Java | easy-explanation-with-diagram-java-by-je-ture | Intuition\n Describe your first thoughts on how to solve this problem. \n\n\nLets forget about the 2d array its confusing. Lets get into game.\nI am playing gam | jeevankumar159 | NORMAL | 2023-01-24T03:14:46.648501+00:00 | 2023-01-24T15:00:08.744815+00:00 | 4,890 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\nLets forget about the 2d array its confusing. Lets get into game.\nI am playing game, I say a position you say me new position. I say 3 you say 3, I say 2 you say 15. But how do you say this?? Using our 2D array.\n\nYou go to position 2 and see 15 and say me 15.\n\nBut how to identify row and column?\n\n\n\nwe can use the above formulas to find the row and column number. So When I say 2 you get r and c using above formula and find 15 at that position.\n\n\nNow\'s the Intersting part.\n# BFS Using ArrayList\n\n\n\nWe add 1 initially to the arrayList, we remove from beginning and find all the new positions that we can go, i.e if we are at 1 --> 15,3,4,5,6,7 and add to arraylist. I have changed arraylist to queue as queues are faster.\n\nwe remove 15 now and find all the new positions we can go.\n\nThe result condition: \nThe positon is destination return steps\nthe arrayList is empty i.e you can\'t go to destination return -1\n\nSince from 3 we can go to 4 but this 4 is already reached by 1, we use a hashmap to store already visited boxes and the number of steps to visit them as values.\n\n\nhttps://youtu.be/A7Vdy9-xTjk\n\n\n\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 int length = 1;\n int [][] board;\n public int snakesAndLadders(int[][] board) {\n this.board = board;\n length = board.length;\n HashMap<Integer,Integer> visited = new HashMap();\n visited.put(1,0);\n Queue<Integer> arr = new LinkedList<>();\n arr.add(1);\n while (!arr.isEmpty()){\n int n = arr.remove();\n for(int i = n+1;i<=n+6;i++){\n int next = i;\n int nextPos = getPosition(i);\n if(next>length*length) return -1;\n if(nextPos!=-1){\n next = nextPos;\n }\n if(next==length*length) return visited.get(n)+1;\n if(!visited.containsKey(next)){\n visited.put(next,visited.get(n)+1 );\n arr.add(next);\n } \n }\n \n }\n return -1;\n }\n\n public int getPosition(int n){\n int row = (n-1)/length;\n int column = (n-1)%length;\n if(row%2!=0){\n column = (column-length+1)*-1;\n }\n row = (row-length+1)*-1;\n \n int result = board[row][column];\n return result;\n }\n}\n``` | 41 | 2 | ['Java'] | 3 |
snakes-and-ladders | 🚀Beats 100%(2ms)🚀 ||✅Easy Solutions✅||🔥Fully Explained🔥|| C++|| Java|| Python3 | beats-1002ms-easy-solutionsfully-explain-wcf2 | Intuition :\n 1. For each step we do the following:\n\n - roll dice (and check all 6 possible values, marking each as visited)\n - check if we land on a l | N7_BLACKHAT | NORMAL | 2023-01-24T05:09:28.286983+00:00 | 2023-01-24T05:25:04.278402+00:00 | 7,629 | false | # Intuition :\n 1. For each step we do the following:\n\n - roll dice (and check all 6 possible values, marking each as visited)\n - check if we land on a ladder and take it (no possibility to skip it, we must take it)\n - remember where to continue next time (add the new position to the queue)\n2. Now let\u2019s take a look at scenarios:\n\n - Just step starting from square 1 with a dice where 6 is the best \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Complexity\n- Time complexity :O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# If you find this solution easy to understand and helpful, then Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n\n\n\n# Code [C++| Java| Python3] - [With Comments]\u2B07\uFE0F\u2B07\uFE0F\u2B07\uFE0F\n```C++ []\ntypedef pair<int,int> Pi;\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int rows=board.size(), cols = board[0].size(), target=rows*cols, r, c, p;\n vector<int> visited(rows*cols + 1); // cells on board start from 1\n // queue contains <priority, square> sorted ascending by priority\n // prio = #steps * 1000 + (500 - square);\n // number of steps is critical and adds 1000; 500 is selected as it is higher than the max cell (20*20=400)\n priority_queue<Pi, vector<Pi>, greater<Pi>> q;\n q.push(make_pair(0,1)); // 0 steps to position 1\n visited[1] = true;\n while(q.size())\n {\n auto step_pos = q.top(); q.pop();\n int s = step_pos.first/1000 + 1;\n \n for(int i=1; i<=6; i++)\n {\n auto p = step_pos.second+i;\n if(visited[p]) continue;\n visited[p] = true;\n \n r = rows - (p-1) / cols - 1;\n c = (p-1) % cols;\n if((rows-r-1)%2) c = cols - c - 1; // change direction for odd lines\n int ladder = board[r][c];\n if(ladder>0 && ladder<=target)\n p = ladder; // no update for steps. allow to come here again with a dice\n \n if(p == target) return s;\n q.push(make_pair(s*1000+500-p, p));\n }\n }\n return -1;\n }\n};\n```\n```Java []\nimport java.util.*;\nclass Solution \n{\n public int snakesAndLadders(int[][] board) \n {\n int rows = board.length, cols = board[0].length, target = rows * cols, r, c, p;\n boolean[] visited = new boolean[rows * cols + 1]; // cells on board start from 1\n // queue contains <priority, square> sorted ascending by priority\n // prio = #steps * 1000 + (500 - square);\n // number of steps is critical and adds 1000; 500 is selected as it is higher than the max cell (20*20=400)\n PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n q.offer(new int[] {0, 1}); // 0 steps to position 1\n visited[1] = true;\n\n while (!q.isEmpty()) \n {\n int[] step_pos = q.poll();\n int s = step_pos[0] / 1000 + 1;\n for (int i = 1; i <= 6; i++) \n {\n p = step_pos[1] + i;\n if (visited[p]) continue;\n visited[p] = true;\n\n r = rows - (p - 1) / cols - 1;\n c = (p - 1) % cols;\n if ((rows - r - 1) % 2 == 1) \n c = cols - c - 1; // change direction for odd lines\n int ladder = board[r][c];\n \n if (ladder > 0 && ladder <= target)\n p = ladder; // no update for steps. allow to come here again with a dice\n if (p == target) \n return s;\n q.offer(new int[] {s * 1000 + 500 - p, p});\n }\n }\n return -1;\n }\n}\n```\n```Python3 []\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n def label_to_position(label):\n r, c = divmod(label-1, n)\n if r % 2 == 0:\n return n-1-r, c\n else:\n return n-1-r, n-1-c\n \n seen = set()\n queue = collections.deque()\n queue.append((1, 0))\n while queue:\n label, step = queue.popleft()\n r, c = label_to_position(label)\n if board[r][c] != -1:\n label = board[r][c]\n if label == n*n:\n return step\n for x in range(1, 7):\n new_label = label + x\n if new_label <= n*n and new_label not in seen:\n seen.add(new_label)\n queue.append((new_label, step+1))\n return -1\n```\n | 40 | 1 | ['Heap (Priority Queue)', 'Python', 'C++', 'Java', 'Python3'] | 4 |
snakes-and-ladders | [c++] bfs easy solution with explanation | c-bfs-easy-solution-with-explanation-by-ib599 | \n\tpair<int, int> coordinates(int x, int n) // find the coordinates given integer\n {\n int r = n - (x-1)/n -1;\n int c = (x-1)%n;\n if | prateekchhikara | NORMAL | 2020-07-06T16:59:53.192444+00:00 | 2020-07-06T17:02:23.651808+00:00 | 4,095 | false | ```\n\tpair<int, int> coordinates(int x, int n) // find the coordinates given integer\n {\n int r = n - (x-1)/n -1;\n int c = (x-1)%n;\n if(r%2==n%2)\n return {r,n-c-1};\n return {r, c};\n }\n int snakesAndLadders(vector<vector<int>>& board) {\n int steps = 0;\n queue<int> q;\n q.push(1);\n int n = board.size();\n vector<vector<bool>> visited(n, vector<bool>(n)); // so that we are not trapped in a loop\n visited[board.size()-1][0]=true;\n while(q.size()!=0) // work until the queue is empty\n {\n int z = q.size();\n for(int i=0; i<z; i++) // for each step use all the elements in the queue\n {\n int x = q.front();\n if(x == n*n) return steps;\n q.pop();\n for(int j=1; j<=6; j++) // all possible moves\n {\n if(j+x > n*n) break;\n pair<int, int> p = coordinates(x+j, n);\n if(visited[p.first][p.second]) continue;\n visited[p.first][p.second] = true;\n if(board[p.first][p.second]!=-1) // if snake or ladder\n q.push(board[p.first][p.second]);\n else\n q.push(j+x);\n }\n }\n steps++;\n }\n return -1;\n }\n``` | 37 | 0 | [] | 10 |
snakes-and-ladders | C++ solution with detailed explanation | c-solution-with-detailed-explanation-by-gkpf3 | \nNote that u are starting from the bottom and u change the direction after finishing every row.\nApproach used here is BFS.\nWe push the start(1) to our queue | leodicap99 | NORMAL | 2020-05-12T02:56:17.587544+00:00 | 2020-05-12T02:56:17.587611+00:00 | 4,024 | false | ```\nNote that u are starting from the bottom and u change the direction after finishing every row.\nApproach used here is BFS.\nWe push the start(1) to our queue and proceed with our BFS.\nWe will explore all the six sides and keep moving forward until I reach r*r where r is the size of the board.\n\nApart from the standard BFS performed here the only tricky part is to find the next step u are going to take becaue of the direction given in question is pretty hard.\n\nNote that if ur board is a 6x6 board ur start which is 1 will be (5,0) 5 denoting the last row and 0 denoting the first column.\nBut another problem arises aprat fromt this,\n\n 7<------Note that after 6 the direction reverses itself and we should be able to tackle this too.\n1 2 3 4 5 6\n\nLets try tackling these two conditions namely:-\n1. We must be able to go bottom to top.\n2. We must be able to flip our direction after every row.\n\nAlgorithm:-\nIts not exactly an algorithm but a simple formula to tackle this.\n\n1.Our row traversal must go like this- 5,4,3,2,1 5(fromt 1 to 6),4(from 7 to 12) and so on....\n\nSo the way to go about it is we divide the number we are at by the board size and u get a number. You subtract the board size with that number and by 1 cuz we start from 0.\nLet me explain\n\nLet num=1\n1/6=0\n6-0-1=5<-- this is the row we are at\nThis will work for 1,2,3,4,5 but not for 6\n6/6=1\n6-1-1=4 but we are still at row 5\nSo the way to tackle this is by using this\nint x=(next_step-1)/row;\nx=row-1-x;\nThis will make 1,2,3,4,5,6 all in the same row.\ncolumn is easy all u have to do is int y=(next_step-1)%row;\n\n\n2. For fliping direction all we are going to dow is we have found x in the previous step.\n so for every odd x we flip the direction and for every even ir we maintain our normal direction.\n if(x%2==1)if(x%2==1)y=row-1-y;\n\n\n vector<int> calc(int row,int next_step)\n {\n int x=(next_step-1)/row;\n int y=(next_step-1)%row;\n if(x%2==1)y=row-1-y;\n x=row-1-x;\n return {x,y};\n }\n int snakesAndLadders(vector<vector<int>>& board) {\n int r=board.size();\n queue<int> q;\n q.push(1);\n int step=0;\n while(!q.empty())\n {\n int n=q.size();\n for(int i=0;i<n;i++)\n {\n int t=q.front();\n q.pop();\n if(t==r*r)return step;\n for(int i=1;i<=6;i++)\n {\n int next_step=t+i;\n if(next_step>r*r)break;\n auto v=calc(r,next_step); \n int row=v[0],col=v[1];\n if(board[row][col]!=-1)\n {\n next_step=board[row][col];\n }\n if(board[row][col]!=r*r+1)\n {\n q.push(next_step);\n board[row][col]=r*r+1;\n }\n }\n }\n step++;\n }\n return -1;\n }\n\n``` | 29 | 1 | ['Breadth-First Search', 'C', 'C++'] | 3 |
snakes-and-ladders | Clean concise easy under-standing solution bfs c++ | clean-concise-easy-under-standing-soluti-61vy | \n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n vector<vector<bool>> visited(n , vector<bool>(n,false));\n \n | ladyengg | NORMAL | 2021-06-02T15:11:02.027151+00:00 | 2021-06-02T15:11:02.027201+00:00 | 2,362 | false | ```\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n vector<vector<bool>> visited(n , vector<bool>(n,false));\n \n queue<int> q;\n q.push(1);\n visited[n-1][0]=true;\n int steps=0;\n while(!q.empty())\n {\n int size=q.size();\n while(size--) /// checking levels for smallest steps , similar to shortest path \n {\n int currpos = q.front();\n if(currpos==n*n)\n return steps;\n q.pop(); \n for(int i=1;i<=6;i++) /// a dice can get 1 to number 6 \n {\n int nextpos=currpos+i;\n if(nextpos>n*n)\n break;\n int r = n - (nextpos-1)/n -1; // getting row of board matrix\n int c = (nextpos-1)%n; // getting column of board matrix\n if(r%2 == n%2) // this step is imp because the value after n will come just above n like 7 will\n c = n-c-1; // come just above 6 and not above 1 , if we are given in other format we can skip this\n if(!visited[r][c])\n {\n visited[r][c]=true;\n if(board[r][c]!=-1)\n q.push(board[r][c]); // if it is ladder or snake push that value else just push next position\n else\n q.push(nextpos);\n }\n }\n }\n steps++;\n }\n return -1; \n }\n\t``` | 28 | 1 | ['Breadth-First Search', 'C'] | 2 |
snakes-and-ladders | Clean Java Solution - BFS | clean-java-solution-bfs-by-mycafebabe-yzjc | \nclass Solution {\n public int snakesAndLadders(int[][] board) {\n if (board == null || board.length == 0 || board[0].length == 0) {\n ret | mycafebabe | NORMAL | 2019-01-05T21:00:12.638230+00:00 | 2019-01-05T21:00:12.638282+00:00 | 4,486 | false | ```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n if (board == null || board.length == 0 || board[0].length == 0) {\n return -1;\n }\n int rows = board.length;\n int cols = board[0].length;\n int dest = rows * cols;\n Queue<Integer> queue = new LinkedList<>();\n queue.offer(1);\n Set<Integer> set = new HashSet<>();\n set.add(1);\n int steps = 0;\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int curr = queue.poll();\n if (curr == dest) {\n return steps;\n }\n for (int diff = 1; diff <= 6 && curr + diff <= dest; diff++) {\n int[] pos = getCoordinate(curr + diff, rows, cols);\n int next = board[pos[0]][pos[1]] == -1 ? curr + diff : board[pos[0]][pos[1]];\n if (!set.contains(next)) {\n queue.offer(next);\n set.add(next);\n }\n }\n }\n steps++;\n }\n return -1;\n }\n \n public int[] getCoordinate(int n, int rows, int cols) {\n int r = rows - 1 - (n - 1) / cols;\n int c = (n - 1) % cols;\n if (r % 2 == rows % 2) {\n return new int[]{r, cols - 1 - c};\n } else {\n return new int[]{r, c};\n }\n }\n}\n``` | 25 | 0 | [] | 8 |
snakes-and-ladders | Python BFS solution | python-bfs-solution-by-cenkay-o5ng | \nclass Solution:\n def snakesAndLadders(self, board):\n arr, nn, q, seen, moves = [0], len(board) ** 2, [1], set(), 0\n for i, row in enumerat | cenkay | NORMAL | 2018-09-23T19:24:05.419788+00:00 | 2018-09-23T19:24:05.419831+00:00 | 3,708 | false | ```\nclass Solution:\n def snakesAndLadders(self, board):\n arr, nn, q, seen, moves = [0], len(board) ** 2, [1], set(), 0\n for i, row in enumerate(board[::-1]): arr += row[::-1] if i % 2 else row\n while q:\n new = []\n for sq in q:\n if sq == nn: return moves \n for i in range(1, 7):\n if sq + i <= nn and sq + i not in seen:\n seen.add(sq + i)\n new.append(sq + i if arr[sq + i] == -1 else arr[sq + i])\n q, moves = new, moves + 1\n return -1 \n``` | 24 | 1 | [] | 8 |
snakes-and-ladders | Python 3 || 16 lines, w/ brief comments || T/S: 98% / 96% | python-3-16-lines-w-brief-comments-ts-98-7pom | \nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \n board.reverse() # <\u2 | Spaulding_ | NORMAL | 2023-01-24T04:44:02.113790+00:00 | 2024-05-31T17:04:28.296456+00:00 | 3,762 | false | ```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \n board.reverse() # <\u2013\u2013 convert the board to 1D list\n for i in range(1,len(board),2): board[i].reverse()\n arr = [None]+list(chain(*board)) # <\u2013\u2013 add an initial element (None) \n # to make indexing simpler\n \n n, queue, seen, ct = len(arr)-1, deque([1]), {1}, 0 \n\n while queue: # <\u2013\u2013 BFS search for arr[n]\n lenQ = len(queue)\n\n for _ in range(lenQ): # <\u2013\u2013 one level of BFS\n\n cur = queue.popleft()\n if cur == n: return ct\n\n for i in range(cur+1, min(cur+7,n+1)): # <\u2013\u2013 oiterate through the possible next moves\n nxt = arr[i] if arr[i]+1 else i # <\u2013\u2013 determine whether snake or ladder\n\n if nxt in seen: continue # <\u2013\u2013 avoid revisiting positions \n seen.add(nxt)\n queue.append(nxt) # <\u2013\u2013 build queue for next level\n \n ct += 1 \n \n return -1\n```\n[https://leetcode.com/problems/snakes-and-ladders/submissions/1273463024/](https://leetcode.com/problems/snakes-and-ladders/submissions/1273463024/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ the number of cells in `board`.\n | 22 | 0 | ['Python3'] | 2 |
snakes-and-ladders | DFS vs BFS vs Djikstra solution. C++ | dfs-vs-bfs-vs-djikstra-solution-c-by-adi-n5ze | Conventional wisdom(and most textbooks) say that for finding shortest path in a graph, you use BFS for unweighted graph and you use Djikstra\'s algorithm for we | aditya991 | NORMAL | 2021-07-05T23:34:02.022478+00:00 | 2021-07-06T04:53:27.253166+00:00 | 2,597 | false | Conventional wisdom(and most textbooks) say that for finding shortest path in a graph, you use BFS for unweighted graph and you use Djikstra\'s algorithm for weighted graphs. But they don\'t say that you cannot use BFS, DFS on weighted graphs. You can modify those algorithms to find the shortest path in weighted graphs too. \n\nIn BFS and DFS, you explore every neighbor of a node only once. With BFS, you can find the shortest path to any given node in a unweighted graph because the first time you visit a node, that would be the shortest path to that node.\n\nBut in the case of weighted graphs, this wouldn\'t be true. Instead what you can do is to make a note of distances to each node from the starting node as you go about traversing the graph. When you find a new path to an already explored node that is shorter than what you previously found, you update it\'s previously recorded distance and re-explore all of it\'s neighbors. This essentially means that you would be visiting the same set of nodes and vertices potentially multiple times. Dijkstra\'s algorithm circumvents this problem by maintaining a sorted queue of all unexplored nodes ordered by their distance from the starting node. The idea is that you would explore a node that is closest to the starting node hoping that it\'s neighbors would also be closest to the starting node. Ofcourse, this assumption would not always be true and in situations where you find a path to a node that is shorter than what you previously found, you have to re-explore the whole set of vertices and nodes connected to that node again.\n\nSimilarly you can apply Dijkstra\'s algorithm to unweighted graphs too. In situations where there are two different edges leading up to the same node, both DFS and BFS pick any vertex on random and proceed. But ideally we should pick a vertex that is shortest to avoid having to re-explore the same bunch of nodes two times. For example:\n\nA -------- B---------C\n\t\t\t\t \n\nSuppose A is 5 units from starting point and C is 10 units from starting point. This is still a unweighted graph. It\'s just that there are way more intermediate nodes between C and the starting point. Now going through A, B is about 6 units from the starting point and C is about 11 units. \n\nWith BFS, DFS there is no garuntee that A and their neighbors would be explored first. If you explore C first, you would have to re-explore B and it\'s neighbors again when you discover A.\n\nDjikstra\'s algorithm works around this problem by maintaing a sorted queue of nodes, ordered by their distances from the starting node.\n\nSo, A->B in that queue would rank higher than C -> B\n\n\n\nNow, to actually solve the problem. First, I will think of this as a shortest path finding problem on a 1D array with node values in the range (1 to NxN). The underlying graph is indeed a **unweighted** graph. Now to be able to read the input, I would need to convert a given number eg. 7 to co-ordinate on the board like {1, 3} so I can read the input matrix.\n\n\nFor that I have this function:\n```\ntuple<int, int> coord(int n, int c) {\n int row = n - 1 - ((c - 1) / n);\n int row_direction = (((n - 1) % 2) == (row % 2));\n int column = c - 1 - ((n - 1 - row) * n);\n column = row_direction ? column : n - column - 1;\n return {row, column};\n }\n```\n\n**DFS:**\n```\nint snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> distances(n * n + 1, -1);\n int target = n * n;\n stack<tuple<int, int>> s({{1, 0}});\n int min_seen = numeric_limits<int>::max();\n while(!s.empty()) {\n int x, distance;\n tie(x, distance) = s.top();\n s.pop();\n if(distances[x] == -1) {\n distances[x] = distance;\n } else {\n distances[x] = min(distances[x], distance);\n }\n int xx, yy;\n tie(xx, yy) = coord(n, x);\n if(board[xx][yy] != -1) {\n x = board[xx][yy];\n if(distances[x] == -1) {\n distances[x] = distance;\n } else {\n distances[x] = min(distances[x], distance);\n }\n }\n if(x == target) {\n min_seen = min(min_seen, distance);\n continue;\n }\n \n for(int i = 1; i <= 6; i++) {\n int neighbor = x + i;\n if(neighbor <= target && (distances[neighbor] == -1 || distances[neighbor] > distance + 1)) {\n s.push({neighbor, distance + 1});\n }\n }\n }\n return min_seen == numeric_limits<int>::max() ? -1 : min_seen;\n }\n```\n\n**BFS:**\n```\nint snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> distances(n * n + 1, -1);\n int target = n * n;\n queue<tuple<int, int>> q({{1, 0}});\n int min_seen = numeric_limits<int>::max();\n while(!q.empty()) {\n int x, distance;\n tie(x, distance) = q.front();\n q.pop();\n if(distances[x] == -1 || distances[x] > distance) {\n distances[x] = distance;\n } else {\n continue;\n }\n int xx, yy;\n tie(xx, yy) = coord(n, x);\n if(board[xx][yy] != -1) {\n x = board[xx][yy];\n }\n if(x == target) {\n min_seen = min(min_seen, distance);\n continue;\n }\n \n for(int i = 1; i <= 6; i++) {\n int neighbor = x + i;\n if(neighbor <= target && distances[neighbor] == -1) {\n q.push({neighbor, distance + 1});\n }\n }\n }\n return min_seen == numeric_limits<int>::max() ? -1 : min_seen;\n }\n```\n\n**Djikstra:**\n```\nint snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> distances(n * n + 1, -1);\n int target = n * n;\n auto comp = [](auto& t1, auto& t2) -> bool { \n return get<0>(t1) == get<0>(t2) ? get<1>(t1) < get<1>(t2) : get<0>(t1) < get<0>(t2); \n };\n priority_queue<tuple<int, int>, vector<tuple<int, int>>, decltype(comp)> q(comp);\n q.push({1, 0});\n int min_seen = numeric_limits<int>::max();\n while(!q.empty()) {\n int x, distance;\n tie(x, distance) = q.top();\n q.pop();\n if(distances[x] == -1 || distances[x] > distance) {\n distances[x] = distance;\n } else {\n continue;\n }\n int xx, yy;\n tie(xx, yy) = coord(n, x);\n if(board[xx][yy] != -1) {\n x = board[xx][yy];\n }\n if(x == target) {\n min_seen = min(min_seen, distance);\n continue;\n }\n \n for(int i = 1; i <= 6; i++) {\n int neighbor = x + i;\n if(neighbor <= target) {\n q.push({neighbor, distance + 1});\n } \n }\n }\n return min_seen == numeric_limits<int>::max() ? -1 : min_seen;\n }\n```\n\nNote that a true a Djikstra\'s algorithm using a priority queue/min-heap has a time complexity of O(V + ElogV) the logV is to keep the vertices sorted according to their lengths.\n\nThe thing is that when I was implementing this solution, I was hitting the time limit when using that idea sorting criteria prescribed in most textbooks. So I took a shortcut of ordering the items in the queue, first by physical closeness to the starting position. I.e. position 2 is closer to 1 than 3 on the numberline(just a hacky huristic that happens to work), secondly if there are two items in the queue for the same node, I sort them by their distance to the starting node. \n\n Algorithm Memory Cpu\n DFS 34.1 MB 308 ms\n\tBFS 15 MB 32 ms\n\tDJIKSTRA 14.6 MB 488 ms\n\nAll three solutions are accepted solutions.\nOther problem similar to this: https://leetcode.com/problems/the-maze-ii/ | 22 | 0 | ['Depth-First Search', 'Breadth-First Search', 'C'] | 6 |
snakes-and-ladders | ⭐ C++ solution || BFS || faster than 98% || with Explanation | c-solution-bfs-faster-than-98-with-expla-ivvn | Intuition\nThe problem is asking us to find the minimum number of moves required to reach the end of a board game represented by a 2D grid (snakes and ladders g | rvdd | NORMAL | 2023-01-24T02:50:10.009274+00:00 | 2023-01-24T12:35:21.942040+00:00 | 6,962 | false | # Intuition\nThe problem is asking us to find the minimum number of moves required to reach the end of a board game represented by a 2D grid (snakes and ladders game). The key observation here is that the board can be represented by a 1D array, where each element in the array corresponds to a cell in the 2D grid. This allows us to use a breadth-first search (BFS) algorithm to traverse the board and find the shortest path to the end.\n\nThe BFS algorithm works by starting from the first cell (0th index in the 1D array) and exploring all its neighboring cells that can be reached in one move (in this case, the next 6 cells in the 1D array). For each of these neighboring cells, we check if it has a snake or ladder and update the next cell accordingly. We also keep track of the distance (number of moves) to each cell and use this information to determine the minimum number of moves required to reach the end.\n\nThe algorithm continues this process until the end cell (last index in the 1D array) is reached, at which point the algorithm returns the minimum number of moves required to reach the end. If the end is not reached, the algorithm returns -1 indicating that it is impossible to reach the end.\n\n# Approach\nThe approach used in this solution is Breadth First Search (BFS). It first flattens the board into a 1D array and then uses a queue to keep track of the current position and the distance from the start. The algorithm starts at the first position (0) and uses a loop to check all possible moves (1-6) from the current position. If the next position has not been visited yet, it updates the distance and pushes it into the queue. If the next position is a snake or ladder, it updates the position to the end of the snake or ladder. The algorithm continues this process until it reaches the end of the board or the queue is empty. If the end of the board is reached, it returns the distance, otherwise, it returns -1.\n\n# Complexity\n- Time complexity:\n $$O(n^2)$$ :\n where n is the size of the board. This is because the algorithm must visit each cell in the board at most once, and the number of cells in the board is n^2.\n\n- Space complexity:\n $$O(n^2)$$ :\n we use an array of size n^2 to store the flattened board and another array of size n^2 to store the distance from each cell to the starting cell. Additionally, we use a queue to keep track of the cells to be visited, which also takes up O(n^2) space in the worst case scenario.\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> flattenedBoard(n * n);\n int index = 0;\n bool leftToRight = true;\n for (int i = n - 1; i >= 0; i--) {\n if (leftToRight) {\n for (int j = 0; j < n; j++) {\n flattenedBoard[index++] = board[i][j];\n }\n } else {\n for (int j = n - 1; j >= 0; j--) {\n flattenedBoard[index++] = board[i][j];\n }\n }\n leftToRight = !leftToRight;\n }\n vector<int> dist(n * n, -1);\n queue<int> q;\n q.push(0);\n dist[0] = 0;\n while (!q.empty()) {\n int curr = q.front();\n q.pop();\n if (curr == n * n - 1) {\n return dist[curr];\n }\n for (int i = 1; i <= 6; i++) {\n int next = curr + i;\n if (next >= n * n) {\n continue;\n }\n if (flattenedBoard[next] != -1) {\n next = flattenedBoard[next] - 1;\n }\n if (dist[next] == -1) {\n dist[next] = dist[curr] + 1;\n q.push(next);\n }\n }\n }\n return -1;\n }\n};\n```\n# Please Upvote\n | 20 | 0 | ['Array', 'Breadth-First Search', 'C++'] | 3 |
snakes-and-ladders | ⭐✅ WORKING C++ CODE || SELF EXPLANATORY COMMENTS | working-c-code-self-explanatory-comments-u35a | WORKING C++ CODE || SELF EXPLANATORY COMMENTS || Inspired by wangzi6147\n\n\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n | SachinSahu | NORMAL | 2022-07-07T03:57:00.644625+00:00 | 2022-12-23T17:27:08.946816+00:00 | 1,106 | false | WORKING C++ CODE || SELF EXPLANATORY COMMENTS || Inspired by wangzi6147\n\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n \n int n = board.size();\n \n int arr[n*n]; // 1D array of size n^2\n \n int i = n-1, j = 0; // starting pos\n \n int index = 0, direction = 1; // 1 is left to right;\n // -1 is right to left\n \n // converting board to 1D array\n while(index<n*n)\n {\n arr[index++] = board[i][j];\n \n if(direction == 1 && j == n-1) // reach row end with +ve direction\n {\n // reverse direction\n direction = -1;\n \n // go up\n i--; \n }\n else if(direction == -1 && j == 0) // reach row start with direction right to left\n {\n // reverse direction\n direction = 1; \n \n // go up\n i--; \n }\n else\n {\n // for all other intermediate columns, just add inc variable to j\n j+=direction; \n }\n }\n \n \n int visited[n*n];\n for(int i = 0; i<n*n; i++)\n visited[i] = 0;\n \n queue<int>q;\n \n int start;\n if(arr[0] > -1)\n start = arr[0] - 1;\n else \n start = 0;\n \n q.push(start); // push the starting point\n visited[start] = 1;\n \n int step = 0; // our final answer\n \n \n // standard BFS algo\n while(!q.empty())\n {\n int size = q.size();\n while(size-->0)\n {\n int pos = q.front();\n q.pop();\n \n if(pos==n*n-1) // if reached destination\n return step;\n \n for(int next = pos+1; next<=min(pos+6, n*n - 1); next++) // we can reach only the next 6 positions fron our current location\n {\n int dest;\n \n if(arr[next]>-1) // if snake or ladder exists\n dest = arr[next]-1; // jump to that given position; here, -1 due to 0-based indexing\n else\n dest = next;\n \n if(!visited[dest])\n {\n visited[dest] = 1;\n q.push(dest); // push our new position into queue\n }\n \n \n }\n \n }\n \n // after each BFS layer covered, we need to incease our answer variable as a new jump is required to move further\n step++;\n }\n \n // when we never even reached our destionation\n return -1;\n }\n};\n``` | 18 | 0 | ['Breadth-First Search', 'C', 'C++'] | 1 |
snakes-and-ladders | Java - Easy Solution with comments (Change board to map + BFS) | java-easy-solution-with-comments-change-615kc | \nclass Solution {\n public int snakesAndLadders(int[][] board) {\n //Step1: Convert board to hashmap to map the board cell number to cell value for e | meltawab | NORMAL | 2020-09-09T02:26:24.838496+00:00 | 2020-09-09T02:26:24.838546+00:00 | 1,943 | false | ```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n //Step1: Convert board to hashmap to map the board cell number to cell value for easier calculation\n int n = board.length;\n HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();\n int start = n * n;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++){\n if ((n-i) % 2 == 0) {\n hm.put(start, board[i][j]);\n } else {\n hm.put(start, board[i][n - j - 1]);\n }\n start--;\n }\n }\n // breadth-first-search\n Queue<Integer> queue = new LinkedList<Integer>();\n HashSet<Integer> hs = new HashSet<Integer>();\n queue.add(1);\n hs.add(1); // For visited cells\n int step = 0; \n while(!queue.isEmpty()){\n int size = queue.size();\n for(int i = 0; i < size; i++){\n int current = queue.poll();\n if (current == n * n) { // Reached the top! winner winner chicken dinner \n return step;\n }\n for(int j = 1; j <= 6; j++){\n int newPoint = current + j;\n if (newPoint > n * n){ \n continue; // We are outside the board now with this choice\n }\n if(hm.get(newPoint) != -1){\n newPoint = hm.get(newPoint); // Either snake or ladder (doesn\'t matter)\n }\n if(!hs.contains(newPoint)){\n queue.add(newPoint);\n hs.add(newPoint);\n }\n }\n }\n step++;\n }\n return -1;\n }\n}\n``` | 17 | 0 | ['Breadth-First Search', 'Java'] | 1 |
snakes-and-ladders | Concise java solution explained without use of complex function to get vertex everytime. | concise-java-solution-explained-without-ysxvp | Following links were very helpful in making me understand the logic of this question.\n1) Covers algorithmn via video \n2) Go through this quicky \n3) To cl | nikeMafia | NORMAL | 2020-02-26T21:05:21.175435+00:00 | 2022-10-21T19:13:32.184319+00:00 | 1,095 | false | Following links were very helpful in making me understand the logic of this question.\n1) [Covers algorithmn via video](https://www.youtube.com/watch?v=1pMNYQmtVVg) \n2) [Go through this quicky](https://www.techiedelight.com/min-throws-required-to-win-snake-and-ladder-game/) \n3) To clear your question properly and logic of taking only one ladder/snake at a time . [TESTCASE](https://leetcode.com/problems/snakes-and-ladders/discuss/447423/Please-verify-this-testcase)\nThere are more downvotes to the question because of the edgy testcases.\n\nTime Complexity O(N^2 + 6* N^2) == O(N^2)\n```\nclass Qentry {\n int vertex;\n int moves;\n \n public Qentry(){\n }\n \n public Qentry(int vertex,int moves){\n this.vertex = vertex;\n this.moves=moves;\n }\n}\nclass Solution {\n \n public int snakesAndLadders(int[][] board) {\n /* convert into 1D array first */\n int N = board.length;\n int totalSquares = N*N;\n if(N==0)\n return 0;\n \n int[] nBoard = new int[N*N + 1];\n int k = 1;\n boolean left2right = true;\n for(int i = N - 1; i >= 0; i--) { /* no of rows time */\n if (left2right) {\n for(int j = 0; j < N; j++) nBoard[k++] = board[i][j];\n }else {\n for(int j = N - 1; j >= 0; j--) nBoard[k++] = board[i][j];\n }\n left2right = !left2right;\n }\n \n int [] visited = new int[N*N +1];\n Queue<Qentry> q = new LinkedList<>();\n \n /* intially add we are out of board so v=0 moves=0 */\n Qentry entry = new Qentry(1,0);\n q.add(entry);\n \n while(!q.isEmpty()){\n \n entry = q.poll();\n int v = entry.vertex;\n \n if(v == totalSquares) \n break;\n \n for(int j=v+1;j<=v+6 && j<=totalSquares; j++ ){\n if(visited[j] == 0){\n Qentry temp = new Qentry();\n temp.moves = entry.moves+1;\n visited[j]=1;\n\n if(nBoard[j]!=-1){\n temp.vertex = nBoard[j];\n }else{\n temp.vertex=j;\n }\n q.add(temp);\n }\n }\n \n }\n if(entry.vertex!=totalSquares){\n return -1;\n }\n return entry.moves;\n }\n}\n``` | 16 | 1 | ['Breadth-First Search', 'Java'] | 1 |
snakes-and-ladders | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | leetcode-the-hard-way-explained-line-by-le34u | \uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord for live discussion.\n\uD83D\uDF | __wkw__ | NORMAL | 2023-01-24T04:43:04.295030+00:00 | 2023-01-24T04:43:04.295070+00:00 | 1,301 | false | \uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast](https://www.youtube.com/watch?v=-hEn4OgGrhI&list=PLBu4Bche1aEWMj1TdpymXbD8Tn8xKVYwj&index=24) if you are interested.\n\n```cpp\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n // reconstruct board to 1D array\n vector<int> g(n * n + 1);\n for (int i = n - 1, k = 1, d = 1; i >= 0; i--, d ^= 1) {\n if (d % 2 == 0) {\n // if the direction is even,\n // we iterate columns from the right to the left\n // e.g. 12 <- 11 <- 10 <- 9 <- 8 <- 7\n for (int j = n - 1; j >= 0; j--) {\n g[k++] = board[i][j];\n }\n } else {\n // if the direction is odd, \n // we iterate columns from the left to the right\n // e.g. 1 -> 2 -> 3 -> 4 -> 5 -> 6\n for (int j = 0; j < n; j++) {\n g[k++] = board[i][j];\n }\n }\n }\n // dijkstra\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;\n q.push({0, 1}); // {dist, pos}\n unordered_map<int, int> vis;\n while (!q.empty()) {\n auto [dist, cur_pos] = q.top(); q.pop();\n // skip if the current position is visited and the dist is greater than that\n if (vis.count(cur_pos) && dist >= vis[cur_pos]) continue;\n // if the current position reaches the square, return dist\n if (cur_pos == n * n) return dist;\n // we need `dist` to reach `cur_pos`\n vis[cur_pos] = dist;\n // we can have at most 6 destinations, try each step\n for (int i = 1; i <= 6; i++) {\n // since we reconstruct the input as a 1D array,\n // we can calculate next_pos by adding `i` to `cur_pos`\n int next_pos = cur_pos + i;\n // skip if it is out of bound\n // e.g. in 34, you can only go to 35 and 36, not any cells after 36 (see example 1)\n if (next_pos > n * n) continue;\n // if the next position is -1, then we can go there\n if (g[next_pos] == -1) {\n q.push({dist + 1, next_pos});\n } else {\n // otherwise, there is a ladder / snake which leads to `g[next_pos]`\n q.push({dist + 1, g[next_pos]});\n }\n }\n }\n // not possible to reach the square\n return -1;\n }\n};\n\n``` | 15 | 0 | ['Breadth-First Search', 'C++'] | 1 |
snakes-and-ladders | JAVA || EASY UNDERSTANDING || BFS || SIMPLE || WITH COMMENTS | java-easy-understanding-bfs-simple-with-k2q9q | Code\n\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n=board.length;\n Map<Integer,Integer>hm=new HashMap<>();\n | shaikhu3421 | NORMAL | 2023-01-24T04:12:35.359465+00:00 | 2023-01-24T04:12:35.359500+00:00 | 2,776 | false | # Code\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n=board.length;\n Map<Integer,Integer>hm=new HashMap<>();\n hm.put(1,0);//as we are starting from 1st position so we are adding 1 and the number of steps taken are 0\n Queue<Integer>q=new LinkedList<>();\n q.add(1);//for starting bfs\n while(!q.isEmpty()){\n int p=q.poll();\n if(p==n*n) return hm.get(p);\n for(int i=p+1;i<=Math.min(p+6,n*n);i++){\n int next=check(i,n);//getting the next most suitable position to jump\n int row=next/n,col=next%n;\n int ns=board[row][col]==-1?i:board[row][col];\n /*normal BFS*/\n if(!hm.containsKey(ns)){\n hm.put(ns,hm.get(p)+1);\n q.offer(ns);\n }\n }\n }\n return -1;\n }\n public static int check(int i,int n){\n int q=(i-1)/n,r=(i-1)%n;\n int row=n-1-q;\n int col=row%2!=n%2?r:n-1-r;\n return row*n+col;\n }\n}\n```\nUPVOTE IF U LIKE THE APPROACH\n | 15 | 1 | ['Breadth-First Search', 'Java'] | 5 |
snakes-and-ladders | Javascript BFS | javascript-bfs-by-hakuin-2hkf | \nvar snakesAndLadders = function(board) {\n const N = board.length;\n const getLoc = (pos) => {\n let row = Math.floor((pos - 1) / N);\n let col = (pos | hakuin | NORMAL | 2019-05-16T23:23:16.238797+00:00 | 2019-05-16T23:23:16.238831+00:00 | 2,027 | false | ```\nvar snakesAndLadders = function(board) {\n const N = board.length;\n const getLoc = (pos) => {\n let row = Math.floor((pos - 1) / N);\n let col = (pos - 1) % N;\n col = (row % 2) === 1 ? N - col - 1 : col;\n row = N - row - 1;\n return [row,col];\n }\n const q = [1];\n const v = {\'1\': 0};\n while(q.length) {\n const n = q.shift();\n if(n === N*N) return v[n];\n for(let i = n+1; i <= Math.min(n+6, N*N); i++) {\n const [r, c] = getLoc(i);\n const next = board[r][c] === -1 ? i : board[r][c];\n if(v[next] === undefined) {\n q.push(next);\n v[next] = v[n] + 1;\n }\n }\n }\n \n return -1;\n};\n``` | 15 | 0 | ['Breadth-First Search', 'JavaScript'] | 0 |
snakes-and-ladders | Python Easy To Understand Code + Explanation O(N) | python-easy-to-understand-code-explanati-3dlz | We do bfs so we can find the smallest number of turns we need to win the game. Any time we are looking for shortest path, we should do bfs. \n\nThe tricky parts | rosemelon | NORMAL | 2019-06-10T02:53:51.205372+00:00 | 2019-06-10T02:53:51.205423+00:00 | 1,453 | false | We do bfs so we can find the smallest number of turns we need to win the game. Any time we are looking for shortest path, we should do bfs. \n\nThe tricky parts here are how the snakes board is initialized. You\'ll notice that we start 1 on the last row instead of the 1st, and that the order of the rows alternate (ie, left -> right, then right -> left). You can use `n - row - 1` or `~row` because that\'s the definition of the complement. If a row is even, we\'re going from left -> right, if a row is odd, the numbers are going right -> left. \n\n`chute` is the value a certain board square. If chute != -1, we can go there.\n\nTime: O(N^2) \nSpace: O(N^2) if we happen to go through the entire board\n\n```\nclass Solution(object):\n def snakesAndLadders(self, board):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n n = len(board)\n q = collections.deque([(1, 0)])\n visited = set([1])\n while q: \n for i in range(len(q)):\n square, turn = q.popleft()\n for i in range(square + 1, square + 7):\n row, col = (i - 1)/n, (i - 1) % n \n chute = board[n - row - 1][col if row % 2 == 0 else n - col - 1]\n if chute > 0: i = chute \n if i == n*n: return turn + 1\n if i not in visited:\n visited.add(i)\n q.append((i, turn + 1))\n return -1 \n \n``` | 13 | 1 | [] | 2 |
snakes-and-ladders | Image Explanation🏆- [Complete Intuition - Simple BFS] - C++/Java | image-explanation-complete-intuition-sim-ulzm | Video Solution (Aryan Mittal) - Link in LeetCode Profile\nSnakes and Ladders by Aryan Mittal\n\n\n\n# Approach & Intution\n\n\n\n\n\n\n\n\n\n\n\n# Code\nC++ []\ | aryan_0077 | NORMAL | 2023-04-09T16:02:09.453506+00:00 | 2023-04-09T16:05:17.258495+00:00 | 1,241 | false | # Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Snakes and Ladders` by `Aryan Mittal`\n\n\n\n# Approach & Intution\n\n\n\n\n\n\n\n\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>> &board) {\n int n = board.size(), lbl = 1;\n vector<pair<int, int>> cells(n*n+1);\n vector<int> columns(n);\n for(int i=0;i<n;i++) columns[i] = i;\n for (int row = n - 1; row >= 0; row--) {\n for (int column : columns) {\n cells[lbl++] = {row, column};\n }\n reverse(columns.begin(), columns.end());\n }\n\n vector<int> dist(n*n+1, -1);\n dist[1] = 0;\n queue<int> q;\n q.push(1);\n while (!q.empty()) {\n int curr = q.front();\n q.pop();\n for (int next = curr + 1; next <= min(curr+6, n*n); next++) {\n auto [row, column] = cells[next];\n int destination = board[row][column] != -1 ? board[row][column] : next;\n if (dist[destination] == -1) {\n dist[destination] = dist[curr] + 1;\n q.push(destination);\n }\n }\n }\n \n return dist[n*n];\n }\n};\n```\n```Java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length, lbl = 1;\n List<Pair<Integer, Integer>> cells = new ArrayList<>();\n Integer[] columns = new Integer[n];\n for (int i = 0; i < n; i++) columns[i] = i;\n \n\n cells.add(new Pair<>(0, 0));\n for (int row = n - 1; row >= 0; row--) {\n for (int column : columns) {\n cells.add(new Pair<>(row, column));\n }\n Collections.reverse(Arrays.asList(columns));\n }\n\n int[] dist = new int[n * n + 1];\n Arrays.fill(dist, -1);\n dist[1] = 0;\n Queue<Integer> q = new LinkedList<>();\n q.add(1);\n while (!q.isEmpty()) {\n int curr = q.poll();\n for (int next = curr + 1; next <= Math.min(curr + 6, n * n); next++) {\n Pair<Integer, Integer> cell = cells.get(next);\n int row = cell.getKey();\n int column = cell.getValue();\n int destination = board[row][column] != -1 ? board[row][column] : next;\n if (dist[destination] == -1) {\n dist[destination] = dist[curr] + 1;\n q.add(destination);\n }\n }\n }\n\n return dist[n * n];\n }\n}\n```\n | 12 | 0 | ['Breadth-First Search', 'Graph', 'C++', 'Java'] | 1 |
snakes-and-ladders | ✅C++ fast solution | c-fast-solution-by-coding_menance-c3l0 | Solution Code\nC++ []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> fla | coding_menance | NORMAL | 2023-01-24T04:30:40.663087+00:00 | 2023-01-24T04:30:40.663139+00:00 | 1,239 | false | # Solution Code\n``` C++ []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> flattenedBoard(n * n);\n int index = 0;\n bool leftToRight = true;\n for (int i = n - 1; i >= 0; i--) {\n if (leftToRight) {\n for (int j = 0; j < n; j++) {\n flattenedBoard[index++] = board[i][j];\n }\n } else {\n for (int j = n - 1; j >= 0; j--) {\n flattenedBoard[index++] = board[i][j];\n }\n }\n leftToRight = !leftToRight;\n }\n vector<int> dist(n * n, -1);\n queue<int> q;\n q.push(0);\n dist[0] = 0;\n while (!q.empty()) {\n int curr = q.front();\n q.pop();\n if (curr == n * n - 1) {\n return dist[curr];\n }\n for (int i = 1; i <= 6; i++) {\n int next = curr + i;\n if (next >= n * n) {\n continue;\n }\n if (flattenedBoard[next] != -1) {\n next = flattenedBoard[next] - 1;\n }\n if (dist[next] == -1) {\n dist[next] = dist[curr] + 1;\n q.push(next);\n }\n }\n }\n return -1;\n }\n};\n```\n\n | 12 | 1 | ['C++'] | 1 |
snakes-and-ladders | C++ || Good Code Quality || BFS Solution and Why DFS won't work ? | c-good-code-quality-bfs-solution-and-why-ymmt | Intuition\nThis problem if we break it down we can easily observe we need a shortest path from 1 to $n^2$ with least moves. For such a problem we tend to use BF | akgupta0777 | NORMAL | 2023-01-24T09:54:18.338213+00:00 | 2024-05-05T05:49:04.520561+00:00 | 717 | false | # Intuition\nThis problem if we break it down we can easily observe we need a shortest path from 1 to $n^2$ with least moves. For such a problem we tend to use BFS or Dijkstra but building a graph for dijkstra is complex so I decided to use BFS since we can use it on matrix as well.\n\n# Approach\nWe maintain a standard BFS Queue which contain current cell we are on and number of moves we played. We will explore all the 6 dice possiblities and push them in queue. Its important to note that we also need to keep track of which cells are we visiting because we may end up in a loop of a ladder to the same position, That\'s why we use a visited array to keep track of cells we visited already.\n\n# Why DFS won\'t work ?\nEven though the constraints n<=20 we still have a problem. In DFS we explore all the cells with thier respective 6 possiblities.\nSo for example \nfor cell 1 possibilities need to explore - [2,3,4,5,6,7]\nsimiliarly for above 6 possibilities we need to explore other 6 possibilites\n2 - [3,4,5,6,7,8]\n3 - [4,5,6,7,8,9]\n4 - [5,6,7,8,9,10]\n5 - [6,7,8,9,10,11]\n6 - [7,8,9,10,11,12]\n7 - [8,9,10,11,12,13]\n\nAnd so on...\nThere will be $6^{n^{2}}$ states where n can be 20 so its definetly will TLE ?\n\n# Can\'t we optimize with DP ?\nEven we use DP here and cached the subproblems there will still be $6^{n}$ possibilities in the worst case here n = 20 at max which results in **3656158440062976** subproblems which still get TLE.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N^2)$$ \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N+N^2)$$ Extra $N^2$ for visited array\n\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n queue<pair<int,int>> q;\n int n = board.size();\n vector<int> visited(n*n+1,0);\n q.push({1,0});\n visited[1]=1;\n int row,col,cell; \n while(!q.empty()){\n auto [current,move] = q.front();\n q.pop();\n for(int dice=1;dice<=6;++dice){\n cell = current+dice;\n if(cell%n==0){\n row = n-(cell/n);\n col = (cell/n)&1?n-1:0;\n }else{\n row = n-(cell/n)-1;\n col = (cell/n)&1?n-(cell%n):(cell%n)-1;\n }\n if(board[row][col]!=-1){\n cell = board[row][col];\n }\n if(cell == n*n) return move+1;\n if(!visited[cell]){\n q.push({cell,move+1});\n visited[cell]=1;\n }\n }\n }\n return -1;\n }\n};\n``` | 11 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'C++'] | 2 |
snakes-and-ladders | ✅C++/JAVA/Python |BFS | Very Simple ✔ | cjavapython-bfs-very-simple-by-xahoor72-enov | Intuition\n Describe your first thoughts on how to solve this problem. \nSimply think of shortest path algo i.e bfs or we can do dijkstra\'s algo .That is what | Xahoor72 | NORMAL | 2023-01-24T10:37:58.379201+00:00 | 2023-01-24T10:46:51.969938+00:00 | 1,046 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply think of shortest path algo i.e bfs or we can do dijkstra\'s algo .That is what we have to do here. For every cell there are 6 possiblilies (dice) so we check the all 6 steps which one will bring us shortest path will take that.And if some where our cell is $$n^2$$ we return our steps. If somewhere we are exceeding $$n^2$$ we will break . Where ever cell is -1 we will just mark the cell number but if its is ladder/snake we have to take the destination of that ladder or snake (i.e where its landing).\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo doing bfs is easy but here we have to take care of 2 things (since our given matrix doeanot start form 0 so we have to amp a column in given matrix way i.e Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.): \n1. **Row number** : $$row= n- (curr-1)/n -1$$\n - As we observe this formula can be derived from one or two examples -1 beacuse of 0 base indexing.\n2. **Column number**:$$ col= (curr-1)\\%n$$ since columns are in zig-zag fashion so check when both row and n is even or both are odd then we have take opposite i.e $$n-1-col$$.\n**Hepfull?UpVote\uD83D\uDD3C:\u2B50**\n# Complexity\n- Time complexity:$$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**C++**\n```C++ []\nclass Solution {\npublic:\n\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n int steps = 0;\n queue<int> q;\n vector<vector<bool>> visited(n, vector<bool>(n, false));\n q.push(1);\n visited[n-1][0] = true;\n while (!q.empty()) {\n int sz = q.size();\n for (int i = 0; i < sz; i++) {\n int f = q.front();\n q.pop();\n if (f == n*n) return steps;\n for (int k = 1; k <= 6; k++) {\n int curr=k+f;\n if (curr > n*n) break;\n int r = n - (curr - 1) / n -1;\n int c = (r%2==n%2)?n-1-(curr-1)%n:(curr-1)%n;\n if (visited[r][c]) continue;\n visited[r][c] = true;\n if (board[r][c] == -1) {\n q.push(curr);\n } else {\n q.push(board[r][c]);\n }\n }\n }\n steps++;\n }\n return -1;\n}\n\n};\n```\n```python []\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n steps = 0\n q = []\n visited = [[False for _ in range(n)] for _ in range(n)]\n q.append(1)\n visited[n-1][0] = True\n while len(q) > 0:\n sz = len(q)\n for i in range(sz):\n f = q[0]\n q.pop(0)\n if f == n*n: \n return steps\n for k in range(1, 7):\n curr = k + f\n if curr > n*n: \n break\n r = n - (curr - 1) // n - 1\n c = (r % 2 == n % 2) ? n-1-(curr-1) % n : (curr-1) % n\n if visited[r][c]: \n continue\n visited[r][c] = True\n if board[r][c] == -1:\n q.append(curr)\n else:\n q.append(board[r][c])\n steps += 1\n return -1\n```\n```JAVA []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int steps = 0;\n Queue<Integer> q = new LinkedList<Integer>();\n boolean visited[][] = new boolean[n][n];\n q.add(1);\n visited[n-1][0] = true;\n while(!q.isEmpty()){\n int size = q.size();\n \n for(int i =0; i <size; i++){\n int x = q.poll();\n if(x == n*n) return steps;\n for(int k=1; k <=6; k++){\n if(k+x > n*n) break;\n int pos[] = findCoordinates(k+x, n);\n int r = pos[0];\n int c = pos[1];\n if(visited[r][c] == true) continue;\n visited[r][c] = true;\n if(board[r][c] == -1){\n q.add(k+x);\n }else{\n q.add(board[r][c]);\n }\n }\n }\n \n steps++;\n \n } \n return -1;\n }\n \n public int[] findCoordinates(int curr, int n) {\n int r = n - (curr - 1) / n -1;\n int c = (curr - 1) % n;\n if (r % 2 == n % 2) {\n return new int[]{r, n - 1 - c};\n } else {\n return new int[]{r, c};\n }\n }\n}\n```\n**UpVote will be Apprecaited** | 10 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C++'] | 1 |
snakes-and-ladders | 100% fast javascript very easy to understand with video explanation! | 100-fast-javascript-very-easy-to-underst-t16z | If you like my video and explanation, Subscribe please!!! Thank you!!\n\nhttps://youtu.be/i91nezWtI7Y\n\n\n\n\n# Code\n\n/**\n * @param {number[][]} board\n * @ | rlawnsqja850 | NORMAL | 2023-01-24T01:49:33.756745+00:00 | 2023-01-24T01:49:33.756775+00:00 | 1,397 | false | If you like my video and explanation, Subscribe please!!! Thank you!!\n\nhttps://youtu.be/i91nezWtI7Y\n\n\n\n\n# Code\n```\n/**\n * @param {number[][]} board\n * @return {number}\n */\nvar snakesAndLadders = function(board) {\n let n = board.length;\n let set = new Set();\n let getPos = (pos) =>{\n let row = Math.floor((pos-1) / n)\n let col = (pos-1) % n\n col = row % 2 == 1 ? n - 1 - col : col;\n row = n - 1 - row;\n return [row,col]\n }\n let q = [[1,0]]\n while(q.length>0){\n [pos,moves] = q.shift();\n for(let i =1; i<7; i++){\n let newPos = i+pos;\n let [r,c] = getPos(newPos);\n if(board[r][c] != -1 ) newPos = board[r][c]\n if(newPos == n*n) return moves+1;\n if(!set.has(newPos)){\n set.add(newPos)\n q.push([newPos,moves+1])\n }\n }\n }\n return -1 \n};\n``` | 10 | 0 | ['JavaScript'] | 3 |
snakes-and-ladders | 📌📌Python3 || ⚡122 ms, faster than 75.83% of Python3 | python3-122-ms-faster-than-7583-of-pytho-g7kc | \ndef snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n board.reverse()\n\n def intToPos(square):\n r = | harshithdshetty | NORMAL | 2023-01-24T03:18:10.653284+00:00 | 2023-01-24T03:18:10.653319+00:00 | 1,847 | false | ```\ndef snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n board.reverse()\n\n def intToPos(square):\n r = (square - 1) // n\n c = (square - 1) % n\n if r % 2:\n c = n - 1 - c\n return [r, c]\n\n q = deque()\n q.append([1, 0]) \n visit = set()\n while q:\n square, moves = q.popleft()\n for i in range(1, 7):\n nextSquare = square + i\n r, c = intToPos(nextSquare)\n if board[r][c] != -1:\n nextSquare = board[r][c]\n if nextSquare == n * n:\n return moves + 1\n if nextSquare not in visit:\n visit.add(nextSquare)\n q.append([nextSquare, moves + 1])\n return -1\n``` | 9 | 0 | ['Python', 'Python3'] | 2 |
snakes-and-ladders | C++ || Explained with comments || BFS | c-explained-with-comments-bfs-by-chandan-5tse | Upvote if you found solution helpful\nC++\nclass Solution {\npublic:\n\tint snakesAndLadders(vector<vector<int>>& board) {\n\t\tint destination = pow(board.size | chandan93 | NORMAL | 2022-06-05T07:45:33.970196+00:00 | 2022-06-05T07:45:33.970233+00:00 | 576 | false | **Upvote if you found solution helpful**\n```C++\nclass Solution {\npublic:\n\tint snakesAndLadders(vector<vector<int>>& board) {\n\t\tint destination = pow(board.size(), 2);\n\t\tint n = board.size();\n\n\t\tint ans = 0;\n\t\t// creating a hashtable for maintaining which cell is visited already\n\t\tunordered_set<int> visited;\n\t\t\n\t\tqueue<int> q;\n\n\t\tq.push(1);\n\t\tvisited.insert(1);\n\n\t\twhile (!q.empty()) {\n\t\t\tint size = q.size();\n\t\t\t\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t// popping current position\n\t\t\t\tint curr_pos = q.front();\n\t\t\t\tq.pop();\n\n\t\t\t\t// now we roll the dice\n\t\t\t\tfor (int dice = 1; dice <= 6; dice++) {\n\t\t\t\t // we have our next position as given below \n\t\t\t\t\tint next_pos = curr_pos + dice;\n\n\t\t\t\t\t// row and column number of that position in board\n\t\t\t\t\tint row = (n-1)-(next_pos - 1) / n;\n\t\t\t\t\tint col = (next_pos - 1) % n;\n\n\t\t\t\t\t// now according to the board we have to flip the row\n\t\t\t\t\t// whenever we encounter odd row number\n\t\t\t\t\tif ((n-1-row) % 2 != 0) {\n\t\t\t\t\t\tcol = n - 1 - col;\n\t\t\t\t\t}\n\n\t\t\t\t\t// now at the next position we may encounter a snake or ladder\n\t\t\t\t\tif (board[row][col] != -1) {\n\t\t\t\t\t\tnext_pos = board[row][col];\n\t\t\t\t\t}\n\n\t\t\t\t\t// case when we reach the destination\n\t\t\t\t\tif (next_pos == destination) {\n\t\t\t\t\t\treturn ans+1;\n\t\t\t\t\t}\n\n\t\t\t\t\t// if the next position is not visited then we \n\t\t\t\t\t// push it in the queue and make it as visited\n\t\t\t\t\tif (visited.count(next_pos) == 0) {\n\t\t\t\t\t\tvisited.insert(next_pos);\n\t\t\t\t\t\tq.push(next_pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tans++;\n\t\t}\n\t\treturn -1;\n\t}\n};\n``` | 9 | 1 | ['Breadth-First Search', 'C'] | 0 |
snakes-and-ladders | [PYTHON] Easy Understanding solution ✔ | python-easy-understanding-solution-by-ra-96uk | The solution may be lengthy but it is readable, fast and easy to understand, dry run it you will surely get the logic its guarantee if still doubt arises ask in | RaghavGupta22 | NORMAL | 2022-04-09T10:09:28.620257+00:00 | 2022-05-08T07:39:53.154285+00:00 | 1,908 | false | The solution may be lengthy but it is readable, fast and easy to understand, dry run it you will surely get the logic its guarantee if still doubt arises ask in comments. \n\n\tclass Solution:\n\t\tdef snakesAndLadders(self, board: List[List[int]]) -> int:\n\t\t\tn=len(board)\n\t\t\tstart, end =1,n*n\n\t\t\tvisited=set()\n\t\t\tqueue=deque()\n\t\t\tqueue.append((start,0)) #initial state before throwing dice\n\t\t\t\n\t\t\t#the purpose of this function is to give row and column value of a cell after adding a move comes on dice\n\t\t\tdef find_coordinates(current_position):\n\t\t\t\trow = n - 1 - (current_position - 1) // n #normal calculation to find row number of a cell\n\t\t\t\tcol = (current_position - 1) % n #normal calculation to find column number of a cell\n\t\t\t\tif row % 2 == n % 2: #board is in Boustrophedon style so handle it we are checking this condition\n\t\t\t\t\treturn (row, n - 1 - col)\n\t\t\t\telse:\n\t\t\t\t\treturn (row, col)\n\n\t\t\twhile queue:\n\t\t\t\tcurr_pos, steps=queue.popleft()\n\t\t\t\tif curr_pos == end: #when player reaches at end, return steps \n\t\t\t\t\treturn steps\n\n\t\t\t\tfor dice in range(1,7): #iterating on all numbers of dices\n\t\t\t\t\tif curr_pos + dice >end: #not valid position to move\n\t\t\t\t\t\tbreak\n\t\t\t\t\tnext_row, next_col = find_coordinates(curr_pos + dice) #got coordinates of row and column\n\t\t\t\t\tif (next_row, next_col) not in visited: #checking that cell is already not visited\n\t\t\t\t\t\tvisited.add((next_row, next_col))\n\t\t\t\t\t\tif board[next_row] [next_col]!=-1: #if there is ladder\n\t\t\t\t\t\t\tqueue.append((board[next_row][next_col],steps+1))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tqueue.append((curr_pos + dice,steps+1))\n\t\t\treturn -1\n\t\t\t\n**PLEASE VOTE ME UP :)** | 9 | 0 | ['Breadth-First Search', 'Python', 'Python3'] | 4 |
snakes-and-ladders | ✅ JAVA || BFS || CLEAND CONCISE READABLE || | java-bfs-cleand-concise-readable-by-bhar-u5sv | THIS QUESTION IS SIMILAR TO ROTTEN ORANGES PROBLEM.THE ONLY CHANGE IS YOU HAVE TO FIND THE ROW AND COLUMN WHICH IS THE HARDEST PART IN THIS QUESTION.TO FIND THE | bharathkalyans | NORMAL | 2022-03-10T06:14:03.345571+00:00 | 2022-03-10T06:14:34.868499+00:00 | 1,174 | false | **THIS QUESTION IS SIMILAR TO ROTTEN ORANGES PROBLEM.THE ONLY CHANGE IS YOU HAVE TO FIND THE ROW AND COLUMN WHICH IS THE HARDEST PART IN THIS QUESTION.TO FIND THE ROW AND COLUMN WE HAVE TO TRY HIT AND TRY METHOD AND COME TO CONCLUSION.\uD83D\uDD25**\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int minSteps = 0;\n int rows = board.length;\n int start = 1, end = rows * rows;\n boolean[][] isVisited = new boolean[rows][rows];\n LinkedList<Integer> queue = new LinkedList<>();\n\n isVisited[rows - 1][0] = true;\n queue.add(start);\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int currentPosition = queue.pop();\n if (currentPosition == end) return minSteps;\n //Rolling Dice upto 6 and adding those possible destinations to Queue.\n for (int dice = 1; dice <= 6; dice++) {\n if (dice + currentPosition > end) break;\n\n int[] nextPosition = findCoordinates(currentPosition + dice, rows);\n int nextRow = nextPosition[0], nextColumn = nextPosition[1];\n if (!isVisited[nextRow][nextColumn]) {\n isVisited[nextRow][nextColumn] = true;\n if (board[nextRow][nextColumn] != -1) queue.add(board[nextRow][nextColumn]);\n else queue.add(currentPosition + dice);\n }\n }\n }\n minSteps++;\n }\n return -1;\n }\n \n\t//Most Important part, rest of the question is simple BFS.\n private int[] findCoordinates(int currentPosition, int n) {\n int r = n - (currentPosition - 1) / n - 1;\n int c = (currentPosition - 1) % n;\n if (r % 2 == n % 2) return new int[]{r, n - 1 - c};\n else return new int[]{r, c};\n }\n}\n```\n**UPVOTE IF HELPFUL\uD83D\uDE4F\uD83C\uDFFB** | 9 | 0 | ['Breadth-First Search', 'Java'] | 1 |
snakes-and-ladders | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-pz5o | Exalanation []\nauthorslog.com/blog/avyU0ff8Pi\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n i | Dare2Solve | NORMAL | 2024-07-19T17:39:13.898754+00:00 | 2024-07-19T17:39:13.898785+00:00 | 1,459 | false | ```Exalanation []\nauthorslog.com/blog/avyU0ff8Pi\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n set<int> visited;\n auto getPos = [&](int pos) {\n int row = (pos - 1) / n;\n int col = (pos - 1) % n;\n if (row % 2 == 1) col = n - 1 - col;\n row = n - 1 - row;\n return make_pair(row, col);\n };\n queue<pair<int, int>> q;\n q.push({1, 0});\n\n while (!q.empty()) {\n auto [pos, moves] = q.front();\n q.pop();\n\n for (int i = 1; i < 7; ++i) {\n int newPos = i + pos;\n auto [r, c] = getPos(newPos);\n\n if (board[r][c] != -1) newPos = board[r][c];\n if (newPos == n * n) return moves + 1;\n\n if (!visited.count(newPos)) {\n visited.insert(newPos);\n q.push({newPos, moves + 1});\n }\n }\n }\n return -1;\n }\n};\n```\n\n```python []\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n \n def getPos(pos: int) -> (int, int):\n row = (pos - 1) // n\n col = (pos - 1) % n\n if row % 2 == 1:\n col = n - 1 - col\n row = n - 1 - row\n return row, col\n\n visited = set()\n queue = deque([(1, 0)]) # (position, moves)\n while queue:\n pos, moves = queue.popleft()\n for i in range(1, 7):\n newPos = pos + i\n if newPos > n * n:\n break\n r, c = getPos(newPos)\n if board[r][c] != -1:\n newPos = board[r][c]\n if newPos == n * n:\n return moves + 1\n if newPos not in visited:\n visited.add(newPos)\n queue.append((newPos, moves + 1))\n \n return -1\n```\n\n```java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Set<Integer> visited = new HashSet<>();\n \n Queue<int[]> queue = new LinkedList<>();\n queue.offer(new int[]{1, 0}); // Start from position 1 with 0 moves\n \n while (!queue.isEmpty()) {\n int[] current = queue.poll();\n int pos = current[0];\n int moves = current[1];\n \n for (int i = 1; i <= 6; i++) {\n int newPos = pos + i;\n if (newPos > n * n) break;\n int[] coordinates = getPos(newPos, n);\n int r = coordinates[0];\n int c = coordinates[1];\n \n if (board[r][c] != -1) newPos = board[r][c];\n if (newPos == n * n) return moves + 1;\n \n if (!visited.contains(newPos)) {\n visited.add(newPos);\n queue.offer(new int[]{newPos, moves + 1});\n }\n }\n }\n return -1;\n }\n private int[] getPos(int pos, int n) {\n int row = (pos - 1) / n;\n int col = (pos - 1) % n;\n if (row % 2 == 1) col = n - 1 - col;\n row = n - 1 - row;\n return new int[]{row, col};\n }\n}\n```\n\n```javascript []\nvar snakesAndLadders = function (board) {\n let n = board.length;\n let set = new Set();\n let getPos = (pos) => {\n let row = Math.floor((pos - 1) / n)\n let col = (pos - 1) % n\n col = row % 2 == 1 ? n - 1 - col : col;\n row = n - 1 - row;\n return [row, col]\n }\n let q = [[1, 0]]\n while (q.length > 0) {\n [pos, moves] = q.shift();\n for (let i = 1; i < 7; i++) {\n let newPos = i + pos;\n let [r, c] = getPos(newPos);\n if (board[r][c] != -1) newPos = board[r][c]\n if (newPos == n * n) return moves + 1;\n if (!set.has(newPos)) {\n set.add(newPos)\n q.push([newPos, moves + 1])\n }\n }\n }\n return -1\n};\n``` | 8 | 0 | ['Graph', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
snakes-and-ladders | java DFS | java-dfs-by-00_11_00-19n6 | \nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n \n int[] moves = new int[n * n + 1];\n | 00_11_00 | NORMAL | 2019-03-29T06:30:49.155710+00:00 | 2019-03-29T06:30:49.155758+00:00 | 969 | false | ```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n \n int[] moves = new int[n * n + 1];\n Arrays.fill(moves, Integer.MAX_VALUE);\n moves[1] = 0;\n \n dfs(1, moves, board);\n return moves[n * n] == Integer.MAX_VALUE? -1: moves[n * n];\n }\n \n private void dfs(int cur, int[] moves, int[][] board) { \n int n = board.length; \n for (int i = 1; i <= 6; ++i) {\n int next = cur + i;\n if (next > n * n) {\n continue;\n }\n \n int snake = getSnake(next, board);\n if (snake != -1) {\n if (moves[snake] > moves[cur] + 1) {\n moves[snake] = moves[cur] + 1;\n dfs(snake, moves, board);\n }\n } else {\n if (moves[cur] + 1 < moves[next]) {\n moves[next] = moves[cur] + 1;\n dfs(next, moves, board);\n }\n }\n }\n }\n \n private int getSnake(int cur, int[][] board) {\n int n = board.length; \n int row = (cur - 1) / n;\n int x = n - 1 - row;\n int y = row % 2 == 0 ? cur - 1 - row * n : n + row * n - cur;\n return board[x][y];\n }\n}\n``` | 8 | 0 | [] | 1 |
snakes-and-ladders | Java || BFS | java-bfs-by-henryzhc-kc5u | \n//The most tricky part is to find the current number row and col\nint r = n - 1 - (num - 1) / n;\nint c = r % 2 != n % 2 ? (num - 1) % n : n - 1 - (num - 1) % | henryzhc | NORMAL | 2023-01-24T02:00:15.657790+00:00 | 2023-01-24T02:00:28.499422+00:00 | 1,606 | false | ```\n//The most tricky part is to find the current number row and col\nint r = n - 1 - (num - 1) / n;\nint c = r % 2 != n % 2 ? (num - 1) % n : n - 1 - (num - 1) % n;\n```\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n boolean[] seen = new boolean[n * n + 1];\n seen[1] = true;\n Deque<Integer> queue = new ArrayDeque<>();\n queue.add(1);\n int steps = 0;\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int curr = queue.poll();\n if (curr == n * n) {\n return steps;\n }\n int min = curr + 1;\n int max = Math.min(curr + 6, n * n);\n for (int next = min; next <= max; next++) {\n int r = n - 1 - (next - 1) / n;\n int c = r % 2 != n % 2 ? (next - 1) % n : n - 1 - (next - 1) % n;\n int dest = board[r][c] != -1 ? board[r][c] : next;\n if (!seen[dest]) {\n queue.offer(dest);\n seen[dest] = true;\n }\n }\n }\n steps++;\n }\n return -1;\n }\n}\n``` | 7 | 0 | ['Breadth-First Search', 'Java'] | 1 |
snakes-and-ladders | ✔ [C++] Solution for 909. Snakes and Ladders | c-solution-for-909-snakes-and-ladders-by-3vqe | \nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) \n {\n int sz = board.size(); int target = sz * sz ;\n unorde | utcarsh | NORMAL | 2022-01-05T05:36:56.309498+00:00 | 2022-01-05T05:36:56.309543+00:00 | 884 | false | ```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) \n {\n int sz = board.size(); int target = sz * sz ;\n unordered_map<int, int> moves; \n moves[1] = 0; // Zero(No) moves when we are in square 1\n queue<int> q ; q.push(1); //BFS method\n \n while(!q.empty())\n {\n int current_sq = q.front(); q.pop();\n \n for(int i=1; i<=6; i++)\n {\n int next_sq = current_sq + i ; \n if(next_sq > target){break;}\n \n int row = (next_sq - 1)/sz ;\n int col = (row % 2 == 0) ? (next_sq - 1) % sz : sz - 1 - ((next_sq-1) % sz) ;\n \n if(board[sz-1-row][col] != -1)\n {\n next_sq = board[sz-1-row][col] ;\n }\n if(moves.count(next_sq) == 0)\n {\n moves[next_sq] = moves[current_sq] + 1;\n if(next_sq == target){return moves[next_sq];}\n q.push(next_sq);\n }\n }\n }\n \n return -1 ;\n }\n};\n``` | 7 | 1 | ['Breadth-First Search', 'C', 'C++'] | 1 |
snakes-and-ladders | [Java] Optimised BFS solution - 2ms (faster than 100%) | java-optimised-bfs-solution-2ms-faster-t-vm2j | The solution is simple BFS where from any square we only visit:\n Snakes or ladders (<= 6 squares away)\n The furthest square without a snake or ladder (<= 6 sq | edlilkid | NORMAL | 2020-11-15T12:55:30.417395+00:00 | 2020-11-15T12:56:23.929916+00:00 | 1,056 | false | The solution is simple BFS where from any square we **only** visit:\n* Snakes or ladders (<= 6 squares away)\n* The furthest square **without** a snake or ladder (<= 6 squares away)\n\nThere is nothing to be gained from visited unoccupied squares *closer* than the furthest unoccupied square. Even when just visiting the furthest square, we are able to visit **all** available snakes and ladders on the board.\n\n## Example Jump\n\n**2** => Current square\n**3** => Contains a ladder (visit)\n**4** => Unoccupied and not furthest (skip)\n**5** => Contains a ladder (visit)\n**6** => Unoccupied and not furthest (skip)\n**7** => Contains a snake (visit)\n**8** => Unoccupied and furthest (visit)\n\nSo **3**, **5**, **7**, and **8** are added to the BFS queue.\n## Code\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n final int n = board.length;\n final int finish = n * n;\n Queue<Integer> queue = new LinkedList<>();\n queue.add(1);\n boolean[] visited = new boolean[finish + 5];\n visited[0] = true;\n int moves = 1;\n \n while (!queue.isEmpty()) {\n int queueN = queue.size();\n for (int i = 0; i < queueN; i++) {\n int current = queue.poll();\n //track the max normal roll (no snakes or ladders)\n int maxNormal = -1;\n for (int next = current + 1; next <= current + 6; next++) {\n int event = board(board, next);\n if (event == -1) {\n //no snakes or ladders => update max normal roll\n maxNormal = next;\n } else {\n if (!visited[event - 1]) {\n //check if reached finish\n if (event >= finish) {\n return moves;\n }\n //add any events to queue\n visited[event - 1] = true;\n queue.add(event);\n }\n }\n }\n if (maxNormal != -1) {\n if (!visited[maxNormal - 1]) {\n //check if reached finish\n if (maxNormal >= finish) {\n return moves;\n }\n //add max normal roll to queue\n visited[maxNormal - 1] = true;\n queue.add(maxNormal);\n }\n }\n }\n moves++;\n }\n return -1;\n }\n \n private int board(int[][] board, int square) {\n final int n = board.length;\n if (square >= n * n) {\n return -1;\n }\n int row = (n - 1) - (square - 1) / n;\n int col = (square - 1) % n;\n if (((square - 1) / n) % 2 == 1) {\n col = (n - 1) - col;\n }\n return board[row][col];\n }\n}\n``` | 7 | 0 | ['Breadth-First Search', 'Java'] | 1 |
snakes-and-ladders | C++ || BFS || Full Explanation | c-bfs-full-explanation-by-7oskaa-k5la | Intuition\nMake a bfs from $1$ to $N^2$\n\n# Approach\nIf we store the min dist for each value we will get the answer\n\n- First we want to store the coordinate | 7oskaa | NORMAL | 2023-01-24T05:34:14.969652+00:00 | 2023-01-24T05:34:14.969697+00:00 | 393 | false | # Intuition\nMake a bfs from $1$ to $N^2$\n\n# Approach\nIf we store the min dist for each value we will get the answer\n\n- First we want to store the coordinate for each value to can access it\n- For each value we will try the 6 possible destinations for it if they are exist\n- If there is a snake of ladder in the next destination we will go for it othwerwise we will go to next destination\n- Calculate the min dist for each value \n\n# Complexity\n- Time complexity:\n$O(N^2)$\n\n- Space complexity:\n$O(N^2)$\n\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n // dimension of the board\n int n = board.size();\n\n // coord[i] will be the coordinate of the cell that value is i\n vector < pair < int, int > > coord(n * n + 1);\n\n // dist for each value\n vector < int > dist(n * n + 1, 1e9);\n\n // assign coordinate the direction is alternating by row\n bool is_right = true;\n for(int r = n, idx = 1; r >= 1; r--){\n if(is_right)\n for(int c = 1; c <= n; c++)\n coord[idx++] = {r, c};\n else\n for(int c = n; c >= 1; c--)\n coord[idx++] = {r, c};\n is_right = !is_right;\n }\n\n // make bfs from 1 to n * n\n queue < int > bfs;\n bfs.push(1);\n dist[1] = 0;\n\n while(!bfs.empty()){\n // current value\n auto u = bfs.front();\n auto [r, c] = coord[u]; \n bfs.pop();\n\n for(int v = u + 1; v <= min(u + 6, n * n); v++){\n // get coordinate of the next value\n auto [new_r, new_c] = coord[v];\n\n // if the next value contains snake or ladder so we will go forward to it\n int next = (board[new_r - 1][new_c - 1] == -1 ? v : board[new_r - 1][new_c - 1]);\n \n // bfs 0-1\n if(dist[next] > dist[u] + 1)\n dist[next] = dist[u] + 1, bfs.push(next);\n }\n }\n\n // if it\'s impossible to reach n * n\n if(dist[n * n] == int(1e9))\n dist[n * n] = -1;\n\n // distance to move to n * n\n return dist[n * n];\n }\n};\n```\n\n<div align= "center">\n<h3>Upvote me</h3>\n\n\n\n</div> | 6 | 0 | ['Breadth-First Search', 'Graph', 'Matrix', 'C++'] | 0 |
snakes-and-ladders | Java🔥| Explanation + FollowUp Questions🔥✅| Easy | | java-explanation-followup-questions-easy-05a6 | Intuition\n Describe your first thoughts on how to solve this problem. \nThis solution covers all these followups:\n- Minimum Steps to reach the ending point\n- | Sanchit_Jain | NORMAL | 2023-09-05T11:46:17.299334+00:00 | 2023-09-05T11:49:18.941292+00:00 | 288 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis solution covers all these followups:\n- Minimum Steps to reach the ending point\n- What if we have a special dice\n- What if we need to know how many ladders or snakes we have used to reach the destination with minimum Steps\n- Different starting point or different ending point\n# Approach\n<!-- Describe your approach to solving the problem. -->\nApproach is described in the Code given below\n# Complexity\n- Time complexity: O(n*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n*n)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n //what if we have changed the dice number, or changing the starting index or changing the ending index\n //so i have covered all possible ways in which this question can be asked\n\n//bfs tip:- for better bfs, we can use marking first and then inserting it in the queue which works faster then removing first and then checking\n public int [] getans(int dice,HashMap<Integer,Integer> map,int si,int ei){\n //if si==ei just directly return \n if(si==ei) return new int [] {0,0,0};\n LinkedList<int[]> que = new LinkedList<>();\n que.addLast(new int[] {si,0,0});\n int level = 0;\n //to stop visiting cells again\n boolean [] vis = new boolean [ei+1];\n vis[si]=true;\n //starting bfs\n while(que.size()!=0){\n int size=que.size();\n while(size-->0){\n int [] rem = que.removeFirst();\n int idx= rem[0];\n int lad = rem[1];\n int sna = rem[2];\n for(int i=1;i<=dice;i++){\n int x =i+rem[0]; //checking all the steps\n if(x<=ei){ //valid points\n if(map.containsKey(x)){ //this means that we have encountered a snake or a ladder\n if(map.containsKey(x)){\n int val = map.get(x); \n if(val==ei) return new int[] {level+1,lad+1,sna};\n if(!vis[val]){\n vis[val]=true;\n //if val>x this means we have a ladder and if less, then it is a snake\n que.addLast(val>x? new int [] {val,lad+1,sna}:new int [] {val,lad,sna+1});\n }\n }\n }\n else{\n //if it is not present in map, then it is a normal cell, so just insert it directly\n if(x==ei) return new int [] {level+1,lad,sna};\n if(!vis[x]){\n vis[x]=true;\n que.addLast(new int [] {x,lad,sna});\n }\n }\n }\n }\n }\n level++;\n }\n return new int [] {-1,0,0};\n }\n public int snakesAndLadders(int[][] board) {\n HashMap<Integer,Integer> map = new HashMap<>();\n int count = 1;\n int n = board.length;\n boolean flag = true;\n //traversing the board in the board game fashion and checking if the count that is representing the cell number, if we encounter something other then -1, then it can be a snake or it can be a ladder and mapping that cell index (i.e count to that number)\n for(int i=n-1;i>=0;i--){\n //traversing in the order of the board\n if(flag){\n for(int j=0;j<n;j++){\n if(board[i][j]!=-1){\n map.put(count,board[i][j]); \n }\n count++;\n flag=false;\n }\n }\n else{\n //reversing the direction\n for(int j=n-1;j>=0;j--){\n if(board[i][j]!=-1){\n map.put(count,board[i][j]);\n }\n flag=true;\n count++;\n }\n }\n }\n //if snake on destination then just return -1;\n if(board[0][0]!=-1) return -1;\n //we only want the minimum steps, but for more conceptual approach for this question, {minm steps,ladders used, snakes used} \n int [] ans = getans(6,map,1,n*n);;\n return ans[0];\n \n }\n}\n```\n\n | 5 | 0 | ['Array', 'Hash Table', 'Breadth-First Search', 'Java'] | 0 |
snakes-and-ladders | ✅✔️Easy and Clean Implementation using BFS || C++ Solution✈️✈️✈️✈️✈️ | easy-and-clean-implementation-using-bfs-81f8b | 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 | ajay_1134 | NORMAL | 2023-08-31T13:28:56.216134+00:00 | 2023-08-31T13:28:56.216180+00:00 | 155 | 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 {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n\n map<int,int>mp;\n\n int cnt = 1;\n for(int i=n-1; i>=0; i--){\n if((n-i-1)%2 == 0){\n for(int j=0; j<n; j++){\n if(board[i][j] != -1){\n mp[cnt] = board[i][j];\n }\n cnt++;\n }\n }\n else{\n for(int j=n-1; j>=0; j--){\n if(board[i][j] != -1){\n mp[cnt] = board[i][j];\n }\n cnt++;\n }\n }\n }\n\n vector<int>vis(n*n+1,0);\n vis[1] = 1;\n\n queue<pair<int,int>>q;\n\n q.push({1,0});\n\n while(!q.empty()){\n int node = q.front().first;\n int steps = q.front().second;\n q.pop();\n if(node == n*n) return steps;\n\n for(int i=1; i<=6; i++){\n if(node+i <= n*n && !vis[node+i] ){\n vis[node+i] = 1;\n if(mp.find(node+i) != mp.end()){\n // vis[mp[node+i]] = 1;\n// This is because when we will \n// get a ladder at the destination then we \n// won\'t be able to use that ladder if we \n// mark that node visited previously.\n q.push({mp[node+i],steps+1});\n }\n else q.push({node+i,steps+1});\n\n }\n }\n }\n\n return -1;\n }\n};\n``` | 5 | 0 | ['Hash Table', 'Breadth-First Search', 'Matrix', 'C++'] | 1 |
snakes-and-ladders | JAVA | BFS | Explained using comments ✅ | java-bfs-explained-using-comments-by-sou-vuhz | Please Upvote \uD83D\uDE07\n---\n\njava []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<Int | sourin_bruh | NORMAL | 2023-01-24T08:46:36.951832+00:00 | 2023-01-24T08:54:15.209791+00:00 | 337 | false | # Please Upvote \uD83D\uDE07\n---\n\n``` java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<Integer> q = new LinkedList<>();\n q.offer(1); // we start from the bottom-left cell\n boolean[][] visited = new boolean[n][n];\n visited[n-1][0] = true; // mark the bottom left cell as visited\n int steps = 0; // steps are initially 0\n // We will perform a BFS\n // We will take each reachable cell i.e. current cell + ( to 6)\n // because a dice will give us number between 1-6\n // and we will perform BFS again on every reachable cell\'s reachable cells\n while (!q.isEmpty()) {\n int size = q.size();\n while (size-- > 0) {\n int curr = q.poll(); // current cell we are on\n // say n = 6, so n*n = 36, that is our final destinaton\n // if we reach that cell, we return the number of steps we\'ve taken\n if (curr == n * n) {\n return steps;\n }\n // now we will roll the dice\n // we will try reaching every new cell by doing +(1 to 6)\n for (int i = 1; i <= 6; i++) {\n int newCell = curr + i; \n // if we are exceeding the final destination, we can\'t make that move\n if (newCell > n * n) {\n break; // so we break out\n }\n // if we can move, we will get the coordinates \n // for our new cell that we\'ve reached\n int[] newPos = findCoordinates(newCell, n);\n int r = newPos[0], c = newPos[1];\n if (visited[r][c]) { // if we already visited that cell\n continue; // we will skip\n }\n // otherwise mark the cell as visited\n visited[r][c] = true;\n // whichever cell we are visiting, we\'ll add the cell number to the queue\n // if the cell has -1, means its a normal cell and we can stay there\n if (board[r][c] == -1) {\n q.offer(newCell);\n } \n // otherwise, it might be a snake or a ladder\n // we will jump to that cell\n else {\n q.offer(board[r][c]);\n }\n }\n }\n // increment steps, because we have taken a step and reached a new cell \n steps++;\n }\n\n // in case we never reached the final destination\n return -1; // we return -1\n }\n\n // This method will give us the coordinates of the cell \n // when we provide it the cell number\n private int[] findCoordinates(int pos, int n) {\n int r = n - (pos - 1) / n - 1;\n int c = (pos - 1) % n;\n if (r % 2 == n % 2) {\n return new int[] {r, n - c - 1};\n } else {\n return new int[] {r, c};\n }\n }\n}\n```\n---\n#### Clean solution:\n``` java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<Integer> q = new LinkedList<>();\n q.offer(1); \n boolean[][] visited = new boolean[n][n];\n visited[n-1][0] = true; \n int steps = 0; \n while (!q.isEmpty()) {\n int size = q.size();\n while (size-- > 0) {\n int curr = q.poll(); \n if (curr == n * n) {\n return steps;\n }\n for (int i = 1; i <= 6; i++) {\n int newCell = curr + i; \n if (newCell > n * n) {\n break; \n }\n int[] newPos = findCoordinates(newCell, n);\n int r = newPos[0], c = newPos[1];\n if (visited[r][c]) { \n continue; \n }\n visited[r][c] = true;\n if (board[r][c] == -1) {\n q.offer(newCell);\n } else {\n q.offer(board[r][c]);\n }\n }\n } \n steps++;\n }\n\n return -1; \n }\n\n private int[] findCoordinates(int pos, int n) {\n int r = n - (pos - 1) / n - 1;\n int c = (pos - 1) % n;\n if (r % 2 == n % 2) {\n return new int[] {r, n - c - 1};\n } else {\n return new int[] {r, c};\n }\n }\n}\n```\n---\n#### Time complexity: $$O(n ^ 2)$$\n#### Space complexity: $$O(n ^ 2)$$ | 5 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Java'] | 1 |
snakes-and-ladders | [Python] BFS can solve the problem; Explained | python-bfs-can-solve-the-problem-explain-fkms | This is a simple BFS problem.\nWhat we need to take care is:\n(1) how to find the next cell of each movement: whenever there is a ladder or snake, we need to ad | wangw1025 | NORMAL | 2023-01-24T05:59:05.034641+00:00 | 2023-01-24T05:59:05.034683+00:00 | 2,491 | false | This is a simple BFS problem.\nWhat we need to take care is:\n(1) how to find the next cell of each movement: whenever there is a ladder or snake, we need to advance to the next cell;\n(2) how to correctly map the cell index to the (row, col) pair\n\nSee the details in code:\n\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n # BFS\n self.nrow = len(board)\n # start == 1, and goal == self.nrow * self.nrow\n goal = self.nrow * self.nrow\n \n queue = [(1, 0)]\n # using a set to remember the visited cell\n visited = set()\n \n while queue:\n cur, step = queue.pop(0)\n if cur == goal:\n return step\n \n for move in range(1, 7):\n ncell = cur + move\n if ncell > goal:\n break\n r, c = self.n2rc(ncell)\n if (r, c) not in visited:\n visited.add((r, c))\n if board[r][c] != -1:\n ncell = board[r][c]\n queue.append((ncell, step + 1))\n \n return -1\n \n \n def n2rc(self, n): \n row = (n - 1) // self.nrow\n row = self.nrow - row - 1\n \n col = (n - 1) % self.nrow\n if (self.nrow - row) % 2 == 0:\n col = self.nrow - col - 1\n return row, col\n``` | 5 | 0 | ['Breadth-First Search', 'Python3'] | 0 |
snakes-and-ladders | C++ || Easy to Understand || BFS | c-easy-to-understand-bfs-by-mohakharjani-mtq5 | \nclass Solution {\npublic:\n int bfs(map<int, int>&mp, int n, int start)\n {\n queue<int>q;\n q.push(start);\n set<int>visited; \n | mohakharjani | NORMAL | 2023-01-24T01:14:40.286633+00:00 | 2023-08-02T02:37:12.046762+00:00 | 3,396 | false | ```\nclass Solution {\npublic:\n int bfs(map<int, int>&mp, int n, int start)\n {\n queue<int>q;\n q.push(start);\n set<int>visited; \n visited.insert(start);\n int steps = 0;\n //==================================================\n while(!q.empty())\n {\n int size = q.size();\n while(size--)\n {\n int curr = q.front();\n q.pop();\n if (curr == n * n) return steps;\n\n for (int next = curr + 1; next <= (curr + 6); next++)\n {\n int actualNext = (mp.count(next))? mp[next] : next; //jump to the next value\n if (visited.find(actualNext) != visited.end()) continue;\n\n visited.insert(actualNext);\n q.push(actualNext);\n }\n }\n steps++;\n }\n //=====================================================\n return -1;\n }\n int snakesAndLadders(vector<vector<int>>& board)\n {\n int n = board.size();\n map<int, int>mp;\n for (int i = n - 1; i >= 0; i--) //moving from bottom to top\n {\n int actualRowIdx = (n - i - 1); //rowIndex from bottom \n int low = (actualRowIdx * n) + 1, high = low + n - 1; //range of values in currRow\n int forwardCellIdx = low, reverseCellIdx = high;\n //for EvenRow Idx => (low->high)\n //fir OddRow Idx => (high->low)\n //===============================================\n for (int j = 0; j < n; j++)\n {\n int actualCellIdx = (actualRowIdx % 2 == 0)? forwardCellIdx : reverseCellIdx;\n if (board[i][j] != -1) mp[actualCellIdx] = board[i][j];\n forwardCellIdx++;\n reverseCellIdx--;\n }\n //================================================\n }\n int ans = bfs(mp, n, 1);\n return ans;\n \n }\n};\n``` | 5 | 0 | ['Breadth-First Search', 'C', 'C++'] | 2 |
snakes-and-ladders | Snakes and Ladder | Java concise solution easy to understand 100% | snakes-and-ladder-java-concise-solution-r8ru5 | \n\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n boolean visited[][] = new boolean[n][n];\n Qu | shagungoyal | NORMAL | 2022-09-12T15:48:26.561898+00:00 | 2023-01-24T04:19:50.126458+00:00 | 538 | false | \n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n boolean visited[][] = new boolean[n][n];\n Queue<Integer> queue = new LinkedList<>();\n queue.add(1);\n visited[n-1][0]=true;\n int steps=0;\n while(!queue.isEmpty()){\n int size = queue.size();\n while(size-->0){\n int x = queue.poll();\n if(x==n*n) return steps;\n for(int k=1;k<=6;k++){\n if(k+x>n*n) continue;\n int pos[] = findCoordinates(k+x,n);\n int row = pos[0],col = pos[1];\n if(visited[row][col]==true) continue;\n visited[row][col]=true;\n if(board[row][col]==-1) queue.add(k+x);\n else queue.add(board[row][col]);\n }\n }\n steps++;\n }\n return -1;\n }\n int[] findCoordinates(int curr,int n){\n int r = n - (curr-1)/n - 1;\n int c = (curr-1) % n;\n if(r%2==n%2) return new int[]{r,n-1-c};\n else return new int[]{r,c};\n }\n}\n```\n\nvideo solution explanation: \n[https://www.youtube.com/watch?v=zWS2fCJGxmU](http://) | 5 | 1 | ['Breadth-First Search', 'Graph', 'Java'] | 2 |
snakes-and-ladders | Python BFS + 1D array | python-bfs-1d-array-by-ermolushka2-533a | ```\nfrom collections import deque\n\nclass Solution(object):\n def snakesAndLadders(self, arr):\n """\n :type board: List[List[int]]\n | ermolushka2 | NORMAL | 2020-07-16T16:35:45.231290+00:00 | 2020-07-16T16:35:45.231339+00:00 | 605 | false | ```\nfrom collections import deque\n\nclass Solution(object):\n def snakesAndLadders(self, arr):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n \n temp = []\n even = True\n for i in range(len(arr)-1, -1, -1):\n if even:\n temp.extend(arr[i])\n else:\n temp.extend(arr[i][::-1])\n even = not even\n\n\n\n n = len(temp)\n target = len(temp)-1\n stack = deque([(0, 0)])\n seen = set()\n\n\n while stack:\n\n ind, steps = stack.popleft()\n \n if ind == target:\n return steps\n for move in [1, 2, 3, 4, 5, 6]:\n n_ind = ind + move\n\n if n_ind < n and n_ind not in seen:\n seen.add(n_ind)\n if temp[n_ind] == -1:\n stack.append((n_ind, steps+1))\n else:\n stack.append((temp[n_ind]-1, steps+1))\n return -1\n \n | 5 | 1 | ['Breadth-First Search', 'Python'] | 3 |
snakes-and-ladders | ✅✅Beats 100%🔥C++🔥Python|| 🚀🚀Super Simple and Efficient Solution🚀🚀||🔥Python🔥C++✅✅ | beats-100cpython-super-simple-and-effici-jk47 | IntuitionTo solve this problem, we employ a Breadth-First Search (BFS) algorithm. BFS is a suitable approach here because it is excellent for finding the shorte | shobhit_yadav | NORMAL | 2025-02-18T00:50:06.578936+00:00 | 2025-02-18T00:50:06.578936+00:00 | 737 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To solve this problem, we employ a Breadth-First Search (BFS) algorithm. BFS is a suitable approach here because it is excellent for finding the shortest path in an unweighted graph, which essentially our game board is. Each roll of the die represents a potential transition from one node (square) to another. Moreover, since snakes and ladders can move the player to non-adjacent nodes, BFS can handle these jumps seamlessly while keeping track of the shortest path.
We maintain a queue to represent game states we need to visit (game states are just positions on the board). We also keep track of visited positions to avoid processing the same state multiple times. For each turn, we consider all reachable positions within a roll of a six-sided die and follow snakes and ladders immediately as they only affect the current move. By gradually exploring all possibilities, we ensure we don't miss any potential paths that might lead to the goal in fewer moves, and once we reach n^2, we can return the number of moves taken.
The function get(x) in the solution converts the label of a square to its coordinates on the board, taking into account the alternating direction of the rows. The use of a set vis ensures that each square is visited no more than once, optimizing the search and avoiding cycles. The BFS loop increments a counter ans which represents the number of moves taken so far until it either finds the end or exhausts all possible paths.
⬆️👇⬆️UPVOTE it⬆️👇⬆️
# Approach
<!-- Describe your approach to solving the problem. -->
The implemented solution approach uses Breadth-First Search (BFS), a popular search algorithm, to efficiently find the shortest path to reach the end of the board from the start. Here's the walkthrough of how the solution functions:
1. BFS Queue: We use a deque (a queue that allows inserting and removing from both ends) to store the squares we need to visit. Initially, the queue contains just the first square 1.
2. Visited Set: A set vis is used to track the squares we have already visited to prevent revisiting and consequently, getting stuck in loops.
3. Move Count: ans is a counter that keeps track of the number of moves made so far. It gets incremented after exploring all possible moves within one round of a die roll.
4. Main Loop: The BFS is implemented in a while loop that continues as long as there are squares to visit in the queue.
5. Exploring Moves: For each current position, we look at all possible positions we could land on with a single die roll (six possibilities at most), which are the squares numbered from curr + 1 to min(curr + 6, n^2). We use the get(x) function to calculate the corresponding board coordinates from a square number.
6. Following Snakes or Ladders: If the calculated position has a snake or ladder (board[i][j] != -1), we move to the destination of that snake or ladder as described by the board (next = board[i][j]).
7. Visiting and Queuing: If the next square (factoring in any snakes or ladders) has not been visited, we add it to the queue and mark it visited.
8. Checking for Completion: If, during the BFS, we reach the last square n^2, we immediately return the number of moves made (ans) since this would represent the shortest path to the end.
9. Return Case: If it is not possible to reach the end - which we know if the queue gets exhausted and the end has not been reached - the function returns -1.
The BFS algorithm, coupled with the correct handling of the unique numbering and presence of snakes and ladders, ensures an optimized search for the quickest path to victory.
# Complexity
- Time complexity: $$O(n^2)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n^2)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
⬆️👇⬆️UPVOTE it⬆️👇⬆️
# Code
```cpp []
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
const int n = board.size();
queue<int> q{{1}};
vector<bool> seen(1 + n * n);
vector<int> arr(1 + n * n);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
arr[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j];
for (int step = 1; !q.empty(); ++step)
for (int sz = q.size(); sz > 0; --sz) {
const int curr = q.front();
q.pop();
for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) {
const int dest = arr[next] > 0 ? arr[next] : next;
if (dest == n * n)
return step;
if (seen[dest])
continue;
q.push(dest);
seen[dest] = true;
}
}
return -1;
}
};
```
```python3 []
class Solution:
def snakesAndLadders(self, board: list[list[int]]) -> int:
n = len(board)
q = collections.deque([1])
seen = set()
arr = [0] * (1 + n * n)
for i in range(n):
for j in range(n):
arr[(n - 1 - i) * n + (n - j if (n - i) % 2 == 0 else j + 1)] = board[i][j]
step = 1
while q:
for _ in range(len(q)):
curr = q.popleft()
for next in range(curr + 1, min(curr + 6, n * n) + 1):
dest = arr[next] if arr[next] > 0 else next
if dest == n * n:
return step
if dest in seen:
continue
q.append(dest)
seen.add(dest)
step += 1
return -1
```
⬆️👇⬆️UPVOTE it⬆️👇⬆️ | 4 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C++', 'Python3'] | 0 |
snakes-and-ladders | Basic BFS traversal w/ steps processed in batches | basic-bfs-traversal-w-steps-processed-in-19sq | Intuition\n- Use BFS to to simulate an expanding set of moves starting at square 1\n- When the BFS reaches the last location, you have reached the end\n- In gra | zeddic | NORMAL | 2023-06-19T23:28:42.414407+00:00 | 2023-06-19T23:28:42.414424+00:00 | 216 | false | # Intuition\n- Use BFS to to simulate an expanding set of moves starting at square 1\n- When the BFS reaches the last location, you have reached the end\n- In graph traversal problems, questions that ask for the "minimal" number of moves hint a BFS traversal as an option\n- When doing the BFS you have two options of tracking the moves count\n - You can encode it with the next step in the work queue\n - You can process your work queue in \'batches\' that share the same move count\n\n# Approach\n- Create a helper function that can take a 1-based board location and lookup the corresponding value in the board. This is a combination of mod and division math.\n- Create a BFS, with a work queue starting at position 1\n - Process the queue in batches of # of steps taken so far\n - For each queue location, you want to find what new locations you can reach.\n - To do this, consider each dice throw between 1 and 6 as possible new locations. If a dice throws would end on a snake/ladder, the possible location is the END of the snake/ladder\n - If one of the possible locations is the winning state, return the steps so far.\n - Otherwise, add each possible new, unseen location to the pending queue.\n\n# Code\n```\nconst DICE = [1, 2, 3, 4, 5, 6];\n\nfunction snakesAndLadders(board: number[][]): number {\n const n = board.length;\n const end = n * n;\n const seen = new Set<number>();\n\n let queue: number[] = [1];\n let steps = 1;\n\n while (queue.length > 0) {\n const pending: number[] = [];\n\n while (queue.length > 0) {\n const i = queue.shift();\n for (const dice of DICE) {\n let loc = i + dice;\n const val = getValue(board, loc);\n if (val !== -1) {\n loc = val;\n }\n\n if (seen.has(loc) || loc > end) {\n continue;\n }\n\n if (loc === end) {\n return steps;\n }\n\n seen.add(loc);\n pending.push(loc);\n }\n }\n\n queue = pending;\n steps++;\n }\n\n\n return -1;\n};\n\nfunction getValue(board: number[][], loc: number): number {\n const pos = loc - 1; // board is 1-based, but data is 0-based\n const n = board.length;\n const rowFromBottom = Math.floor(pos / n);\n const row = n - 1 - rowFromBottom; \n\n const offset = pos % n;\n const isBackwards = rowFromBottom % 2 === 1;\n \n const col = isBackwards ? n - 1 - offset : offset;\n\n return board[row]?.[col];\n}\n\n\n``` | 4 | 0 | ['TypeScript'] | 1 |
snakes-and-ladders | BFS Intuition and Approach explained! Code with comments | C++ | HashMap | bfs-intuition-and-approach-explained-cod-aicr | Intuition:\n \tWhenever there\'s a problem that has the word \'minimim\' the problem could be of the following categories:\nDP/ Greedy/ BFS but as there was a g | adityabijapurkar | NORMAL | 2023-01-24T07:21:49.395980+00:00 | 2023-01-24T07:21:49.396014+00:00 | 156 | false | ***Intuition:***\n* \tWhenever there\'s a problem that has the word \'minimim\' the problem could be of the following categories:\nDP/ Greedy/ BFS but as there was a grid (or a graph) involved, it could be considered as a BFS problem\n\n***Approach:***\n* Only if we could get the \'x\' and \'y\' indices of the current position the problem becomes very easy!\nAlso we don\'t want to search the entire board for getting the values as we might need to search for a position multiple times\n\n* The only data structure that comes to mind is a hash map (unordered_map in case of C++)\n\n***Steps:***\n1. \t Store the x/y index of a board in ```Boustrophedon style``` (typical snake and ladders board we used to play on)\n1. \t Start with the starting index ```1```\n1. \t Continue with normal BFS, to simulate a dice roll we use a ```for``` loop from ```1-6```\n1. \t To avoid infinite loops we remark the indices with a high value \n (*ex*: ladder from 1 going to 10, snake from 10 going to 1)\n1. \tIncrement total moves after every iteration and return it after target is reached\n\n***C++ Code:***\n```\nclass Solution {\nprivate:\n// hash_map used to store all indices of positions from 1-n\xB2\n unordered_map<int,pair<int,int>> pos;\n\n// for Boustrophedon style we start from last row and alternate columns each consecutive row \n void givePositions(int n){\n bool LtR=true; //left-right direction\n int curr=1;\n for(int i=n-1;i>=0;i--){\n if(LtR){\n for(int j=0;j<n;j++)\n pos[curr++]={i,j};\n }\n else{\n for(int j=n-1;j>=0;j--)\n pos[curr++]={i,j};\n }\n LtR=!LtR;\n }\n }\n \npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size(), target=pow(n,2);\n givePositions(n);\n \n int moves=0;\n queue<int> q;\n\t\t// start with position 1\n q.push(1);\n \n while(!q.empty()){\n\t\t// normal BFS using queue\n int size=q.size();\n \n while(size--){\n int curr=q.front();\n q.pop();\n\t\t\t\t// target is reached\n if(curr==target)\n return moves;\n \n\t\t\t\t// to simulate a dice roll\n for(int i=1;i<=6;i++){\n int next=curr+i;\n\t\t\t\t\t// if next position goes out of bounds, we stop the search from that position\n if(next>target) break;\n int next_x=pos[next].first, next_y=pos[next].second;\n\t\t\t\t\t\n\t\t\t\t\t// checking if already visited\n if(next_x==INT_MAX && next_y==INT_MAX) continue;\n\t\t\t\t\t// remarking position to avoid infinite loops\n pos[next]={INT_MAX,INT_MAX};\n\t\t\t\t\t\n\t\t\t\t\t// in case of a snake and ladder push the position it takes us to in the queue\n if(board[next_x][next_y]!=-1)\n q.push(board[next_x][next_y]);\n\t\t\t\t\t// else push the position itself\n else\n q.push(next);\n }\n }\n // increment moves after 1 unsuccessful search\n moves++;\n }\n\t\t// if it is impossible to reach the final target\n return -1;\n }\n};\n```\n\nFeel free to comment any suggessions or doubts\nI hope you found this useful, please ```upvote``` if this helped you :)\n | 4 | 0 | ['Breadth-First Search', 'Graph', 'C', 'C++'] | 0 |
snakes-and-ladders | C++ | BFS | Approach Easy Explained | Board modification Explained | c-bfs-approach-easy-explained-board-modi-iqd5 | class Solution {\npublic:\n //\n //Time complexity is O(n2) as we are using a visited array, otherwise exponential 6^n\n \n //we create a map of sna | jprathamesh | NORMAL | 2022-09-08T04:40:58.357475+00:00 | 2022-09-08T04:44:48.985099+00:00 | 1,101 | false | class Solution {\npublic:\n //\n //Time complexity is O(n2) as we are using a visited array, otherwise exponential 6^n\n \n //we create a map of snakes and ladders squares where key is the square where the snake/ladder starts and value is the square where that snake/ladder ends\n \n \n // at each square we enqueue the next 6 squares with a distance of 1 step, meaning that we can reach the next 6 squares from our current square in 1 step or 1 move\n // if any of the next sqauares have a snake or ladder, we enqueue the sqaure where the snake/ladder takes us\n // for this while enqueuing we check in our map if the square we are trying to enqueue has a snake or ladder\n // if it does then we enqueue that sqaure from map\n // if we reach our destination square we return the steps\n //since we are traversing using BFS, our returned steps will be minimum required steps to reach the end\n \n\t//Board Modification\n\t// Board -> actual snake and ladder board which is shown in the question\n\t//Matrix -> Given matrix as input\n\n\t// Given board is in the form of matrix\n\t// The matrix\'s first row is the last row of the board, so to make our traversal more intuitive, we reverse the rows of the given matrix\n\t// The direction of traversal of the board is alternating for each row, so we reverse alternate rows, so that we can traverse through the matrix as we normally do\n\n\n int BFS(vector<vector<int>>& board, unordered_map<int,int> &mp, vector<int> &visited, int n)\n {\n queue<pair<int,int>> Q;\n \n pair<int,int> start = make_pair(0,0);\n \n Q.push(start);\n \n while(!Q.empty())\n {\n auto curr = Q.front();\n Q.pop();\n \n int currSq = curr.first;\n int currSteps = curr.second;\n \n for(int i=1;i<7;i++)\n {\n int newSq = currSq + i;\n \n if( mp.find(newSq) != mp.end())\n newSq = mp[newSq];\n \n if( newSq == (n*n)-1 ) return currSteps+1;\n\n if(!visited[newSq])\n {\n cout<<"currSq is "<<currSq<<" "<<" newSq is "<<newSq<<endl;\n cout<<"currSteps is "<<currSteps<<" newSteps is "<<currSteps+1<<endl;\n Q.push(make_pair(newSq,currSteps+1));\n visited[newSq] = 1;\n }\n \n \n }\n }\n \n return -1;\n \n }\n \n int snakesAndLadders(vector<vector<int>>& board) {\n \n int n = board.size();\n unordered_map<int,int> mp;\n vector<int> visited(n*n, 0);\n \n \n //We reverse the board to make our traversing through indexes easier / more intuitive\n reverse(board.begin(),board.end());\n \n //for every odd row we reverse the row because the traversal of the board is alternating and we need to traverse it that way\n for(int i=0;i<n;i++)\n if(i%2)\n reverse(board[i].begin(),board[i].end());\n \n //we create a map of snakes and ladders \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(board[i][j] != -1)\n mp[(i*n) + j] = board[i][j] - 1; \n }\n }\n \n //BFS\n return BFS(board, mp, visited, n);\n \n \n }\n}; | 4 | 0 | ['Breadth-First Search', 'C'] | 0 |
snakes-and-ladders | C++ solution Easy and Efficient | c-solution-easy-and-efficient-by-baibhav-hr1j | \nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n vector<vector<int>> vis(n,vector<int>( | baibhavsaikia | NORMAL | 2022-08-28T20:47:12.670017+00:00 | 2022-08-28T20:47:12.670056+00:00 | 412 | false | ```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n vector<vector<int>> vis(n,vector<int>(n,0));\n queue<int> q;\n q.push(1);\n vis[n-1][0]=1;\n int c=0;\n while(!q.empty()){\n int size=q.size();\n for(int i=0;i<size;i++){\n int curr=q.front();\n q.pop();\n if(curr==n*n) return c;\n for(int j=1;j<=6;j++){\n int next=curr+j;\n if(next>n*n) break;\n int row=n-1-(next-1)/n;\n int col=(next-1)%n;\n if(row%2==n%2) col=n-col-1;\n if(!vis[row][col]){\n vis[row][col]=1;\n if(board[row][col]!=-1) q.push(board[row][col]);\n else q.push(next);\n }\n }\n }\n c++;\n }\n return -1;\n }\n};\n``` | 4 | 1 | ['Breadth-First Search', 'C'] | 0 |
snakes-and-ladders | easy to understand bfs c++ clean code tricky steps commented | easy-to-understand-bfs-c-clean-code-tric-4r1c | Tips :\nTry to think for simple numbered grid (not boustrophedonical as here) \nthen modify the code\n\nclass Solution {\npublic:\n int snakesAndLadders(vect | user5536c | NORMAL | 2021-02-23T15:21:30.637937+00:00 | 2021-03-01T10:19:48.270723+00:00 | 221 | false | Tips :\nTry to think for simple numbered grid (not boustrophedonical as here) \nthen modify the code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size(), d = n*n, moves = 0;\n queue<int> q;\n q.push(1);\n vector<bool> vis(d+1,0);\n vis[1]=1;\n while(q.size()!=0) \n {\n int z = q.size();\n for(int k=0; k<z; k++)\n {\n int u = q.front();\n q.pop();\n if(u == d)\n return moves;\n for(int i=1; i<=6; i++)\n {\n if(u+i < d+1 && !vis[u+i])\n {\n\t\t\t\t\t\t//mark it visited here so that if tail lies here don\'t take that snake in future\n vis[u+i] = 1;\n //extract row number and column number from current position\n int x = (u+i-1) / n ; \n int y = (u+i-1) % n;\n //adjust according to given format i.e. boustrophedonically\n x = n-x-1; \n if(x%2==n%2)\n y = n-y-1;\n \n if(board[x][y]!=-1) \n q.push(board[x][y]);\n else\n q.push(u+i);\n }\n }\n }\n moves++;\n }\n return -1;\n }\n};\n``` | 4 | 0 | [] | 0 |
snakes-and-ladders | Java solution with descriptive variables for easy understanding | java-solution-with-descriptive-variables-tyc3 | Same solution as given by LC but some descriptive variables for easy understanding\n\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n | CodeMyWayOut | NORMAL | 2020-05-31T15:44:55.975194+00:00 | 2020-05-31T15:46:01.878506+00:00 | 650 | false | Same solution as given by LC but some descriptive variables for easy understanding\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n if (board == null || board.length == 0)\n return -1;\n \n int n = board.length;\n \n Map<Integer, Integer> squareDistanceMap = new HashMap<>();\n squareDistanceMap.put(1, 0);\n \n // most accessible squares from starting square get enqueued first\n Queue<Integer> accessibilityQueue = new LinkedList<>();\n accessibilityQueue.offer(1);\n \n while(!accessibilityQueue.isEmpty()) {\n int polledSquareNumber = accessibilityQueue.poll();\n \n if (polledSquareNumber == n * n)\n return squareDistanceMap.get(polledSquareNumber);\n \n for (int nextSquare = polledSquareNumber + 1; nextSquare <= Math.min(polledSquareNumber + 6, n * n); nextSquare++) {\n int nextSquareBoardCoordinates = generateBoardCoordinates(nextSquare, n);\n int nextSquareRow = nextSquareBoardCoordinates / n;\n int nextSquareCol = nextSquareBoardCoordinates % n;\n \n int squareNumberToEnqueue = board[nextSquareRow][nextSquareCol] == -1? nextSquare : board[nextSquareRow][nextSquareCol];\n if(!squareDistanceMap.containsKey(squareNumberToEnqueue)) {\n squareDistanceMap.put(squareNumberToEnqueue, squareDistanceMap.get(polledSquareNumber) + 1);\n accessibilityQueue.offer(squareNumberToEnqueue);\n }\n }\n }\n \n return -1;\n }\n \n public int generateBoardCoordinates(int squareNumber, int n) {\n // subtract by 1 because square numbers start from 1 and not 0 where as board rows and columns are 0 indexed\n int quotient = (squareNumber - 1) / n;\n int remainder = (squareNumber - 1) % n;\n \n // the game starts from last row and moves to 0th row of board in a reverse manner as it progresses\n int rowNumber = n - 1 - quotient;\n \n /* \n direction of column number changes depending on 2 factors -\n a) the row number\n b) how many rows there are in total. The 0th row for n = 4 will have right to left increasing column numbers\n whereas 0th row for n = 5 will have left to right increasing column numbers\n */\n int columnNumber = rowNumber % 2 != n % 2? remainder : n - 1 - remainder;\n \n return rowNumber * n + columnNumber;\n }\n}\n``` | 4 | 0 | ['Breadth-First Search', 'Java'] | 0 |
snakes-and-ladders | C# | Adapted Solution for Readability | c-adapted-solution-for-readability-by-ma-6n1e | I know a lot of us were having a tough time understanding the solution, so I tried adapting it to (hopefully) make it more readable. \n\npublic class Solution { | mattjordan0887 | NORMAL | 2020-05-22T20:56:59.610810+00:00 | 2020-05-22T20:56:59.610844+00:00 | 147 | false | I know a lot of us were having a tough time understanding the solution, so I tried adapting it to (hopefully) make it more readable. \n```\npublic class Solution {\n public int SnakesAndLadders(int[][] board) \n {\n int n = board.Length;\n int destination = n*n;\n \n Dictionary<int, int> distance = new Dictionary<int, int>();\n // The distance to square one is zero, since we start on square one\n distance.Add(1, 0);\n \n // Queue holds the "square number" -> 1...n\n Queue<int> q = new Queue<int>();\n // Start at "square" one\n q.Enqueue(1);\n\n while (q.Count > 0)\n {\n int currentSpot = q.Dequeue();\n\n if (currentSpot == destination) return distance[currentSpot];\n \n // Try next 6 spots (since dice is 6-sided) or until we reach the end\n for (int nextSpot = currentSpot+1; nextSpot <= Math.Min(currentSpot+6, destination); nextSpot++)\n {\n (int row, int col) coords = convertToBoardCoords(nextSpot, n);\n \n int next = board[coords.row][coords.col] == -1 ? nextSpot : board[coords.row][coords.col];\n \n if (!distance.ContainsKey(next))\n {\n distance.Add(next, distance[currentSpot] + 1);\n q.Enqueue(next);\n }\n }\n }\n \n return -1;\n }\n \n private (int row, int col) convertToBoardCoords(int location, int n)\n {\n int quotient = (location - 1) / n;\n int remaining = (location - 1) % n;\n \n // the zero-based "first row" - quotient\n int currentRow = (n - 1) - quotient;\n int currentCol = 0;\n \n if (currentRow % 2 != n % 2)\n {\n // for rows that are numbered left -> right\n currentCol = remaining;\n }\n else\n {\n // for rows that are numbered right -> left\n currentCol = n - 1 - remaining; \n }\n \n return (currentRow, currentCol);\n }\n \n private void write(string message)\n {\n Console.WriteLine(message);\n }\n}\n``` | 4 | 0 | [] | 0 |
snakes-and-ladders | Python BFS 1D Array | python-bfs-1d-array-by-xbox360555-no6m | BFS\n\n# BFS\nclass Solution:\n def snakesAndLadders(self, board):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n | xbox360555 | NORMAL | 2018-09-23T04:04:42.799684+00:00 | 2018-09-27T01:09:45.836957+00:00 | 838 | false | # BFS\n```\n# BFS\nclass Solution:\n def snakesAndLadders(self, board):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n N = len(board)\n visited = [False] * (N * N)\n a = []\n s = -1\n \n # Translate the board into an array a, with index from \n # 0 to N * N - 1\n for i in range(N - 1, -1, -1):\n j = 0\n s = s * (-1)\n while j < N:\n if s == 1:\n a.append(board[i][j])\n else:\n a.append(board[i][N - 1 - j])\n j += 1\n \n # BFS part\n q = []\n q.append(0)\n visited[0] = True\n res = 0\n while len(q) > 0:\n size_q = len(q)\n for i in range(0, size_q, 1):\n j = q.pop(0)\n if j == N**2 - 1:\n return res\n for k in range(1, 7):\n if j + k > N**2 - 1:\n continue\n if a[j + k] == -1:\n p = j + k\n else:\n p = a[j + k] - 1\n if visited[p]:\n continue\n visited[p] = True\n q.append(p)\n res += 1\n return -1\n``` | 4 | 0 | [] | 0 |
snakes-and-ladders | Simple BFS.(Java) | simple-bfsjava-by-poorvank-2hel | ``` public class SnakeAndLadders { private class Cell { private int id; private int minMovesFromStart; Cell(int id) { this.id = id; } | poorvank | NORMAL | 2018-09-23T03:14:28.833743+00:00 | 2018-09-23T03:15:17.088131+00:00 | 1,167 | false | ```
public class SnakeAndLadders {
private class Cell {
private int id;
private int minMovesFromStart;
Cell(int id) {
this.id = id;
}
Cell() {
}
}
public int snakesAndLadders(int[][] board) {
Queue<Cell> queue = new LinkedList<>();
queue.add(new Cell(1));
int n = board.length*board.length;
boolean[] visited = new boolean[n+1];
visited[1]=true;
Map<Integer,Integer> map = getCellValueMap(board);
while (!queue.isEmpty()) {
int v = queue.peek().id;
if(v==n) {
break;
}
Cell current = queue.poll();
for (int j=(v+1);j<=(v+6) && j<=n;j++) {
if(!visited[j]) {
visited[j]=true;
Cell cell = new Cell();
cell.minMovesFromStart = current.minMovesFromStart+1;
if(map.containsKey(j)) {
cell.id=map.get(j);
} else {
cell.id=j;
}
queue.add(cell);
}
}
}
return !queue.isEmpty()?queue.peek().minMovesFromStart:-1;
}
// Get Snake and ladder end positions if any.
private Map<Integer,Integer> getCellValueMap(int[][] board) {
boolean flag = true;
Map<Integer,Integer> map=new HashMap<>();
int val=1;
for (int i=board.length-1;i>=0;i--) {
if(flag) {
for (int j=0;j<=board.length-1;j++) {
if(board[i][j]!=-1) {
map.put(val,board[i][j]);
}
val++;
}
} else {
for (int j=board.length-1;j>=0;j--) {
if(board[i][j]!=-1) {
map.put(val,board[i][j]);
}
val++;
}
}
flag=!flag;
}
return map;
}
}
``` | 4 | 1 | [] | 1 |
snakes-and-ladders | Python3 Solution - Simplify the board and win | python3-solution-simplify-the-board-and-ijbag | Approach - Preprocessing the boardThe basic idea is to approach it as a basic BFS problem, since we want to find the minimum number of moves to get to the end. | kobyl125 | NORMAL | 2025-01-23T19:40:09.171885+00:00 | 2025-01-23T19:40:09.171885+00:00 | 331 | false | # Approach - Preprocessing the board
The basic idea is to approach it as a basic BFS problem, since we want to find the minimum number of moves to get to the end. One big simplification is turning the 2d board into a 1d list, since we notice that both snakes and ladders are simply shortcuts to a different square.
There are just 2 points to note when converting to a list:
* Parse from the last row to the first row
* Alternate left/right right/left
* For all elements which are not -1, subtract 1 since the problem is 1-indexed
That is actually 3 points! Interesting.
# BFS Time
There are a few things to consider when planning the BFS.
* The shortest path may involve going backwards, so don't take the greedy approach
* It may be impossible to get to the end, so if the queue is empty return `-1`
I added `(index, moves)` to the queue. For each queue element, we add each possible roll to the queue. It is important to have the `seen` set as part of this step before we add things to the queue to meet performance requirements.
# Code
```python3 []
from collections import deque
class Solution:
def board_to_list(self, board: list[list[int]]) -> list[int]:
parse_left = True
output = []
for row in range(len(board) - 1, -1, -1):
if parse_left:
output.extend(board[row])
parse_left = False
else:
output.extend(reversed(board[row]))
parse_left = True
for i in range(len(output)):
if output[i] != -1:
output[i] -= 1
return output
def snakesAndLadders(self, board: list[list[int]]) -> int:
linear = self.board_to_list(board)
size = len(linear)
queue = deque()
queue.append((0, 0))
seen = set([0])
while queue:
(spot, moves) = queue.popleft()
for roll in range(1, 7):
new_spot = spot + roll
if new_spot >= size:
continue
next_spot = linear[new_spot]
if next_spot == -1:
next_spot = new_spot
if next_spot == size - 1:
return moves + 1
if next_spot not in seen:
seen.add(next_spot)
queue.append((next_spot, moves + 1))
# should not get here unless it is impossible to get to the end
return -1
``` | 3 | 0 | ['Python3'] | 1 |
snakes-and-ladders | KOTLIN and JAVA solution | kotlin-and-java-solution-by-anlk-1w5h | \u2618\uFE0F\u2618\uFE0F\u2618\uFE0F If this solution was helpful, please consider upvoting! \u2705\n\n# Intuition\nThe problem can be modeled as finding the sh | anlk | NORMAL | 2024-11-14T20:44:17.593675+00:00 | 2024-11-14T20:44:17.593704+00:00 | 163 | false | \u2618\uFE0F\u2618\uFE0F\u2618\uFE0F If this solution was helpful, please consider upvoting! \u2705\n\n# Intuition\nThe problem can be modeled as finding the shortest path in an unweighted graph:\n\n- Each square on the board is a node.\n- A dice roll determines the edges (connections between nodes).\n- Snakes and ladders directly redirect you to a specific node.\n\nWe can use BFS to solve this, as it ensures the shortest path in an unweighted graph.\n\n# Approach\n- Map the board to a 1D array: \n - Since the board alternates in direction (Boustrophedon style), map it into a single-dimensional array for easier processing.\n- Perform BFS:\n - Start at square 1.\n - For each square, simulate dice rolls (up to 6 moves forward) to determine potential next positions.\n - If a square leads to a snake or ladder, jump to the destination.\n - Use a visited array to avoid revisiting nodes.\n- Terminate BFS:\n - If the last square is reached, return the number of moves.\n - If BFS completes without reaching the last square, return -1.\n\n# Complexity\n- Time complexity: $$O(n.n)$$\n \n\n- Space complexity: $$O(n.n)$$\n\n# Code\n```Kotlin []\nclass Solution {\n fun snakesAndLadders(board: Array<IntArray>): Int {\n val n = board.size\n\n // flatten the board into a 1D array\n val flatBoard = IntArray(n * n + 1)\n var idx = 1\n var leftToRight = true\n\n for (i in n - 1 downTo 0) {\n if (leftToRight) {\n for (j in 0 until n) {\n flatBoard[idx++] = board[i][j]\n }\n } else {\n for (j in n - 1 downTo 0) {\n flatBoard[idx++] = board[i][j]\n }\n }\n leftToRight = !leftToRight\n }\n\n // bfs to find the shortest path\n val queue: Queue<Int> = LinkedList()\n val visited = BooleanArray(n * n + 1)\n queue.add(1)\n visited[1] = true\n var moves = 0\n while (queue.isNotEmpty()) {\n repeat(queue.size) {\n val curr = queue.poll()\n if (curr == n * n) return moves\n\n for (dice in 1..6) {\n var next = curr + dice\n if (next > n * n) break\n\n if (flatBoard[next] != -1) {\n next = flatBoard[next]\n }\n\n if (!visited[next]) {\n visited[next] = true\n queue.add(next)\n }\n }\n }\n moves++\n }\n return -1 \n }\n}\n```\n\n```Java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n\n // flatten the board into a 1D array\n int[] flatBoard = new int[n * n + 1];\n boolean leftToRight = true;\n int idx = 1;\n for (int i = n - 1; i >= 0; i--) {\n if (leftToRight) {\n for (int j = 0; j < n; j++) {\n flatBoard[idx++] = board[i][j];\n }\n } else {\n for (int j = n - 1; j >= 0; j--) {\n flatBoard[idx++] = board[i][j];\n }\n }\n leftToRight = !leftToRight;\n }\n\n // BFS to find the shortest path\n Queue<Integer> queue = new LinkedList<>();\n boolean[] visited = new boolean[n * n + 1];\n queue.add(1);\n visited[1] = true;\n int moves = 0;\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int curr = queue.poll();\n if (curr == n * n) {\n return moves;\n }\n\n for (int dice = 1; dice <= 6; dice++) {\n int next = curr + dice;\n if (next > n * n) break;\n\n if (flatBoard[next] != -1) {\n next = flatBoard[next];\n }\n\n if (!visited[next]) {\n visited[next] = true;\n queue.add(next);\n }\n }\n }\n moves++;\n }\n return -1;\n }\n}\n``` | 3 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Java', 'Kotlin'] | 0 |
snakes-and-ladders | ✅99% BEATS | BFS | JAVA | EXPLAINED🔥🔥🔥 | 99-beats-bfs-java-explained-by-adnannsha-mkcl | Initial Setup:\nWe calculate the destination which is the last cell on the board (i.e., n * n).\nWe create a visited array to track which cells we\'ve already v | AdnanNShaikh | NORMAL | 2024-09-08T16:17:00.332056+00:00 | 2024-09-08T16:17:00.332094+00:00 | 379 | false | **Initial Setup:**\nWe calculate the destination which is the last cell on the board (i.e., n * n).\nWe create a visited array to track which cells we\'ve already visited to avoid cycles and redundant checks.\n\n**BFS Initialization:**\nBFS starts from cell 1, and the queue is initialized with this starting cell.\nWe keep a counter ans to record the number of moves required to reach the destination.\n\n**BFS Processing:**\nFor each cell in the current level (all cells reachable in one move from the previous level), simulate rolling a die (from 1 to 6).\nFor each die roll, calculate the new cell nc. If nc is beyond the destination, we can immediately return the number of moves.\nIf the new cell hasn\'t been visited, determine the effective cell c by checking for snakes or ladders (getCell function).\nAdd the resulting cell to the queue if it\'s valid and hasn\'t been visited.\n\n**Helper Function (getCell):**\nConverts the 1D cell number to its corresponding 2D position on the board, considering the direction of movement (left-to-right or right-to-left) depending on the row number.\nThis function returns the value in the board at that calculated position.\n\n**Termination:**\nThe BFS will return the minimum moves required to reach the destination. If the queue empties without reaching the destination, it returns -1.\n\n# Code\n```java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int destination = board.length * board.length; // Calculate the destination cell number\n boolean[] visited = new boolean[destination + 1]; // Array to keep track of visited cells\n Deque<Integer> q = new ArrayDeque<>(); // Queue to perform BFS\n q.add(1); // Start BFS from the first cell\n visited[1] = true; // Mark the first cell as visited\n int ans = 0; // This will keep track of the number of moves\n\n // BFS loop\n while (!q.isEmpty()) {\n ans++; // Increment move count at each level of BFS\n int size = q.size();\n for (int i = 0; i < size; i++) {\n int f = q.poll(); // Get the current cell number\n boolean added = false; // Flag to ensure we add only one new node per dice roll\n for (int j = 6; j > 0; j--) { // Simulate all dice rolls from 6 to 1\n int nc = f + j; // Calculate new cell number after rolling the die\n if (nc >= destination) // If we reach or exceed the destination, return the result\n return ans;\n if (!visited[nc]) { // If the new cell hasn\'t been visited\n int c = getCell(board, nc); // Get the actual position considering snakes/ladders\n if (c == destination) // If the move lands exactly on the destination\n return ans;\n if ((c == -1 || c == nc) && !added) { // No snake/ladder or it leads to the same position\n q.offer(nc); // Add the position to the queue\n added = true; // Ensure we only add once per dice roll\n } else if (c > 0) { // If there is a snake/ladder that leads to a different cell\n q.offer(c); // Add the destination cell after the snake/ladder to the queue\n }\n visited[nc] = true; // Mark the new cell as visited\n }\n }\n }\n }\n return -1; // If we exit the loop without finding the destination, return -1\n }\n\n // Helper function to calculate the 2D coordinates on the board from a 1D cell number\n int getCell(int[][] board, int k) {\n int n = board.length; // The size of the board\n int r = n - 1 - (k-1) / n; // Row index, counting from the bottom of the board\n int c = 0;\n if (n % 2 == 1) // If the number of rows is odd\n c = (r % 2 == 0 ? (k-1) % n : n - 1 - (k-1) % n); // Compute the column index based on row direction\n else // If the number of rows is even\n c = (r % 2 == 0 ? n - 1 - (k-1) % n : (k-1) % n); // Compute the column index based on row direction\n return board[r][c]; // Return the value at the calculated cell\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
snakes-and-ladders | Short and Easy || BFS || HashSet and Queue | short-and-easy-bfs-hashset-and-queue-by-fx5pq | \nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<int[]> queue = new LinkedList<>();\n q | spats7 | NORMAL | 2023-10-12T02:52:57.830175+00:00 | 2023-10-12T02:52:57.830198+00:00 | 500 | false | ```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n Queue<int[]> queue = new LinkedList<>();\n queue.add(new int[]{1,0});\n Set<Integer> visited = new HashSet<>();\n visited.add(1);\n while(!queue.isEmpty()){\n \n int[] arr = queue.poll();\n int index = arr[0];\n if(index==n*n){\n return arr[1];\n }\n \n for(int idx=index+1; idx <= (Math.min(index+6, n*n)); idx++){\n \n int quotient = (idx-1) / n;\n int row = (n-1)-(quotient);\n int remainder = (idx-1) % n;\n int col = quotient%2==0 ? remainder : (n-1)-remainder; \n \n int next = board[row][col] != -1 ? board[row][col] : idx;\n\n if(visited.contains(next))\n continue;\n visited.add(next);\n queue.add(new int[]{next, arr[1]+1});\n }\n } \n return -1;\n }\n}\n``` | 3 | 0 | ['Breadth-First Search', 'Queue', 'Ordered Set', 'Java'] | 0 |
snakes-and-ladders | Why not dijkstra? w/ Explanation for beginner understanding (Simple) | why-not-dijkstra-w-explanation-for-begin-w41h | Why not dijkstra?\n1. Using priority queue doesn;t make sense as we are moving in sequential order from visiting nodes with 1 distance then visiting nodes with | ankitkumarhello20 | NORMAL | 2023-02-14T11:27:07.991276+00:00 | 2023-06-26T17:12:34.681818+00:00 | 569 | false | Why not dijkstra?\n1. Using priority queue doesn;t make sense as we are moving in sequential order from visiting nodes with 1 distance then visiting nodes with 2 distance and so on.\n2. Then if(dist[dest]>dist[curr]+1) becomes useless as by visiting the node first time has the shortest path , so this condition won\'t be true anytime in the travesal.\n\nThese are the reasons why simple bfs is enough and using dijkstra (which is nothing but using above two conditions in bfs) just consumes time.\n\n(here distance between two directly accessible nodes is same 1 step for everybody, could be any other number but have to be same for everybody)\n\nDijkstra becomes useful in weighted graph where distance to visit one node to other is different hence using above conditions makes sense.\n\nDijkstra algorithm below-\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>> &board) {\n int n = board.size();\n vector<pair<int, int>> cells(n * n + 1);\n int label = 1;\n vector<int> columns(n);\n iota(columns.begin(), columns.end(), 0);\n for (int row = n - 1; row >= 0; row--) {\n for (int column : columns) {\n cells[label++] = {row, column};\n }\n reverse(columns.begin(), columns.end());\n }\n vector<int> dist(n * n + 1, -1);\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;\n dist[1] = 0;\n q.emplace(0, 1);\n while (!q.empty()) {\n auto [d, curr] = q.top();\n q.pop();\n //if(curr==n*n) return d; //Tip: It is better to break out at this point then waiting queue to process all the remaining things and get empty\n for (int next = curr + 1; next <= min(curr + 6, n * n); next++) {\n auto [row, column] = cells[next];\n int destination = board[row][column] != -1 ? board[row][column] : next;\n if (dist[destination] == -1 || dist[curr] + 1 < dist[destination]) {\n dist[destination] = dist[curr] + 1;\n q.emplace(dist[destination], destination);\n }\n }\n }\n return dist[n * n];\n }\n};\n```\nFollowing will also work as explained above (Faster)\n```\n queue<pair<int,int>> q;\n dist[1] = 0;\n q.emplace(0, 1);\n while (!q.empty()) {\n auto [d, curr] = q.front();\n if(curr==n*n) return d;\n q.pop();\n for (int next = curr + 1; next <= min(curr + 6, n * n); next++) {\n auto [row, column] = cells[next];\n int destination = board[row][column] != -1 ? board[row][column] : next;\n if (dist[destination] == -1) {\n dist[destination] = dist[curr] + 1;\n q.emplace(dist[destination], destination);\n }\n }\n }\n```\nno need to set -1 to destination/cost array (or vis array very extra) though setting -1 as opposed to 1e9 will consume less memory\n// as can be seen as visited because dist won\'t be adapted once already for the same thing(true for directed/undirected both)\n\t//here queue can be used at cost to reach next destination is always constant(1) so first encounter is the lowest// though you can always wait to empty to queue/priority_queue but why to waste time\n// if we are using priority queue then waiting it to empty would be same as queue\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>> &board) {\n int n = board.size();\n vector<pair<int, int>> cells(n * n + 1);\n int label = 1;\n vector<int> columns(n);\n iota(columns.begin(), columns.end(), 0);\n for (int row = n - 1; row >= 0; row--) {\n for (int column : columns) {\n cells[label++] = {row, column};\n }\n reverse(columns.begin(), columns.end());\n }\n vector<int> dist(n * n + 1, 1e9);\n queue<pair<int,int>> q;\n dist[1] = 0;\n q.emplace(0, 1);\n while (!q.empty()) {\n auto [d, curr] = q.front();\n if(curr==n*n) return d; // always break at this recommended\n q.pop();\n for (int next = curr + 1; next <= min(curr + 6, n * n); next++) {\n auto [row, column] = cells[next];\n int destination = board[row][column] != -1 ? board[row][column] : next;\n if (dist[destination] >dist[curr]+1) {\n dist[destination] = dist[curr] + 1;\n q.emplace(dist[destination], destination);\n }\n }\n }\n return -1;// didnpt reach\n // return (dist[n * n]==1e9)?-1;\n }\n}; | 3 | 0 | ['Breadth-First Search'] | 0 |
snakes-and-ladders | ✅Accepted | | ✅Easy solution || ✅Short & Simple || ✅Best Method | accepted-easy-solution-short-simple-best-mw71 | \n# Code\n\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n queue<int> q;\n vecto | sanjaydwk8 | NORMAL | 2023-01-26T04:15:46.462143+00:00 | 2023-01-26T04:15:46.462175+00:00 | 78 | false | \n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n queue<int> q;\n vector<bool> v(n*n+1, false);\n vector<int> nums;\n nums.push_back(0);\n int c=0;\n for(int i=n-1;i>=0;i--)\n {\n if(c%2==0)\n for(int j=0;j<n;j++)\n nums.push_back(board[i][j]);\n else\n for(int j=n-1;j>=0;j--)\n nums.push_back(board[i][j]);\n c++;\n }\n int ans=1;\n int s=1;\n if(nums[s]!=-1)\n s=nums[s];\n v[s]=true;\n q.push(s);\n if(s==n*n)\n return ans;\n while(!q.empty())\n {\n int sz=q.size();\n for(int j=0;j<sz;j++)\n {\n int t=q.front();\n q.pop();\n for(int i=t+1;i<=min(t+6, n*n);i++)\n {\n int k=i;\n if(nums[i]!=-1)\n k=nums[i];\n if(v[k]==true)\n continue;\n if(k==n*n)\n return ans;\n q.push(k);\n v[k]=true;\n }\n }\n ans++;\n if(ans>n*n)\n return -1;\n }\n return -1;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!! | 3 | 0 | ['C++'] | 1 |
snakes-and-ladders | Why not simplest BFS template | See this | why-not-simplest-bfs-template-see-this-b-c324 | YouTube Link : https://www.youtube.com/watch?v=26IT3FYm5h8\n\nclass Solution {\npublic:\n int n;\n \n pair<int, int> getCoord(int s) {\n int row | mazhar_mik | NORMAL | 2023-01-24T14:38:09.802893+00:00 | 2023-01-24T14:38:09.802925+00:00 | 158 | false | YouTube Link : https://www.youtube.com/watch?v=26IT3FYm5h8\n```\nclass Solution {\npublic:\n int n;\n \n pair<int, int> getCoord(int s) {\n int row = n-1-(s-1)/n;\n \n int col = (s-1)%n;\n \n if((n%2==1 && row%2==1)||(n%2==0 && row%2==0))\n col = n-1-col;\n \n return make_pair(row, col);\n }\n \n int snakesAndLadders(vector<vector<int>>& board) {\n n = board.size();\n \n int steps = 0;\n queue<int> que;\n \n vector<vector<bool>> visited(n, vector<bool>(n, false));\n visited[n-1][0] = true;\n \n que.push(1);\n vector<bool> seen(n*n+1,false);\n \n \n while(!que.empty()) {\n \n int N = que.size();\n while(N--) {\n \n int x = que.front();\n que.pop();\n\n if(x == n*n)\n return steps;\n\n for(int k = 1; k<=6; k++) {\n if(x+k > n*n)\n break;\n\n pair<int, int> coord = getCoord(x+k);\n int r = coord.first;\n int c = coord.second;\n if(visited[r][c] == true)\n continue;\n\n visited[r][c] = true;\n if(board[r][c] == -1)\n que.push(k+x);\n else {\n que.push(board[r][c]);\n }\n }\n }\n steps++;\n }\n \n return -1;\n }\n};\n``` | 3 | 0 | [] | 0 |
snakes-and-ladders | C++ || BFS || Easy & Faster than 97% 🔥 | c-bfs-easy-faster-than-97-by-me__nik-bd6e | Approach\n Describe your approach to solving the problem. \n1. store ladders and snakes in map through board(given array).\n2. Make a visited bool array and pus | me__nik | NORMAL | 2023-01-24T06:45:40.823589+00:00 | 2023-01-24T07:40:13.693165+00:00 | 1,278 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. store ladders and snakes in map through board(given array).\n2. Make a visited bool array and push visited values in a queue.\n3. check if ladder/snake present at current grid or not, and push max value reachable to queue.\n4. iterate over all possibilities of dice.\n\n# Complexity\n- Time complexity: O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nPlz Upvote :)\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n if(board[0][0] == 1) return -1;\n int n = board.size(), cnt = 0, tcnt = n;\n map<int, int> lad, snk;\n // iteration for storing from rows , which is counting from left to right. \n for(int i = n-1; i>=0; i-=2){\n for(int j = 0; j<n; j++){\n cnt++;\n if(board[i][j] < cnt and board[i][j] != -1){\n snk[cnt] = board[i][j];\n }\n else if(board[i][j] > cnt and board[i][j] != -1){\n lad[cnt] = board[i][j];\n }\n }\n cnt+=n;\n }\n\n // iteration for storing from rows , which is counting from right to left.\n for(int i = n-2; i>=0; i-=2){\n for(int j = n-1; j>=0; j--){\n tcnt++;\n if(board[i][j] < tcnt and board[i][j] != -1){\n snk[tcnt] = board[i][j];\n }\n else if(board[i][j] > tcnt and board[i][j] != -1){\n lad[tcnt] = board[i][j];\n }\n }\n tcnt+=n;\n }\n\n\n // cout<<"snakes"<<endl;\n // for(auto i: snk){\n // cout<<i.first<<" "<<i.second<<endl;\n // }\n // cout<<"ladder"<<endl;\n // for(auto i: lad){\n // cout<<i.first<<" "<<i.second<<endl;\n // }\n\n vector<bool> v(n*n+1, false);\n bool found = false;\n queue<int> q;\n q.push(1);\n v[1] = true;\n int res = 0;\n while(!q.empty() and !found){\n int sz = q.size();\n while(sz--){\n int tmp = q.front();\n q.pop();\n for(int die = 1; die<7; die++){\n if(tmp + die == n*n) found = true;\n\n if((tmp+die<=n*n) && lad[tmp+die] && !v[lad[tmp + die]]){\n v[lad[tmp+die]] = true;\n if(lad[tmp+die] == n*n) found = true;\n q.push(lad[tmp+die]);\n }\n\n else if((tmp+die<=n*n) && snk[tmp+die] && !v[snk[tmp + die]]){\n v[snk[tmp+die]] = true;\n if(snk[tmp+die] == n*n) found = true;\n q.push(snk[tmp+die]);\n }\n\n else if((tmp+die<=n*n) && !v[tmp+die] && !snk[tmp+die] && !lad[tmp+die]){\n v[tmp+die] = true;\n q.push(tmp+die);\n }\n }\n }\n res++;\n }\n return found==0 ? -1 : res;\n }\n};\n``` | 3 | 0 | ['Breadth-First Search', 'Queue', 'Ordered Map', 'C++'] | 1 |
snakes-and-ladders | Simple || JAVA || 101 % Working || Beginners | simple-java-101-working-beginners-by-moh-7558 | 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 | Moh-Sameer-Khan | NORMAL | 2023-01-24T06:31:20.307646+00:00 | 2023-01-24T06:31:20.307685+00:00 | 834 | 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 public int snakesAndLadders(int[][] board) {\n \n int n = board.length, end = n*n, result = 0;\n Queue<Integer> q = new LinkedList<>();\n \n q.add(1);\n \n while( !q.isEmpty() ){ \n result++;\n int size = q.size();\n \n while( size --> 0 ){\n int curr = q.poll();\n for( int i = 1; i <= 6; i++ ) {\n \n int next = curr+i;\n \n int[] rc = getRowCol(next, n);\n \n next = board[rc[0]][rc[1]] == -1 ? next : board[rc[0]][rc[1]];\n \n if( next == -2 ) continue;\n \n if( next >= end ) return result;\n \n q.add(next);\n board[rc[0]][rc[1]] = -2;\n }\n }\n }\n return -1;\n}\n\nprivate int[] getRowCol(int num, int n){\n \n num--;\n \n int r = n-1-num/n, c = -1;\n \n if( ((n-1)&1) == (r&1) ){//Same parity\n c=num%n;\n }else{\n c = n-num%n-1;\n }\n return new int[]{r,c};\n}\n}\n``` | 3 | 0 | ['Java'] | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.