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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-moves-to-spread-stones-over-grid | Backtracking solution | backtracking-solution-by-jkoppula-l133 | \n# Code\n\nclass Solution {\n public int minimumMoves(int[][] grid) {\n List<Cell> emptyCells = new ArrayList<>();\n List<Cell> excessCells = | jkoppula | NORMAL | 2024-01-23T18:03:38.428194+00:00 | 2024-01-23T18:03:38.428228+00:00 | 225 | false | \n# Code\n```\nclass Solution {\n public int minimumMoves(int[][] grid) {\n List<Cell> emptyCells = new ArrayList<>();\n List<Cell> excessCells = new ArrayList<>();\n \n for(int row=0;row<3;row++){\n for(int col=0;col<3;col++){\n if(grid[row][col] == 0){\n emptyCells.add(new Cell(row, col, 0));\n } else if(grid[row][col]>1){\n excessCells.add(new Cell(row, col, grid[row][col]));\n }\n }\n }\n if(emptyCells.size() == 0) return 0;\n\n return helper(0, emptyCells, excessCells);\n }\n\n int helper(int index, List<Cell> emptyCells, List<Cell> excessCells){\n int minMoves = Integer.MAX_VALUE;\n if(index < emptyCells.size()) {\n for(Cell cell: excessCells){\n if(cell.stones > 1){\n cell.stones -= 1;\n int currMoves = Math.abs(emptyCells.get(index).row - cell.row) + Math.abs(emptyCells.get(index).col - cell.col);\n minMoves = Math.min(minMoves, currMoves + helper(index+1, emptyCells, excessCells));\n cell.stones += 1;\n }\n }\n }\n return minMoves == Integer.MAX_VALUE?0:minMoves;\n }\n\n\n\n class Cell{\n int row;\n int col;\n int stones;\n\n Cell(int row, int col, int stones){\n this.row = row;\n this.col = col;\n this.stones = stones;\n }\n }\n}\n``` | 4 | 0 | ['Backtracking', 'Java'] | 1 |
minimum-moves-to-spread-stones-over-grid | Video Solution | Explanation With Drawings | In Depth | C++ | Java | video-solution-explanation-with-drawings-e34l | Intuition and approach discussed in detail in video solution\nhttps://youtu.be/0Yk5KFD9gm0\n\n# Code\n\nclass Solution {\npublic:\n int minMovs = -1;\n in | Fly_ing__Rhi_no | NORMAL | 2023-09-10T16:44:26.145118+00:00 | 2023-09-10T16:44:26.145140+00:00 | 1,588 | false | # Intuition and approach discussed in detail in video solution\nhttps://youtu.be/0Yk5KFD9gm0\n\n# Code\n```\nclass Solution {\npublic:\n int minMovs = -1;\n int minimumMoves(vector<vector<int>>& grid) {\n minMovs = INT_MAX;\n int rows = grid.size(), cols = grid[0].size();\n vector<pair<int, int>> zeros, ones;\n for(int r = 0; r<rows; r++){\n for(int c = 0; c < cols; c++){\n if(grid[r][c] > 1){\n ones.push_back(make_pair(r, c));\n }else if(grid[r][c] == 0){\n zeros.push_back(make_pair(r, c));\n }\n }\n }\n findMoves(zeros, ones, 0, 0, grid);\n return minMovs;\n }\n void findMoves(vector<pair<int, int>> & zeros, vector<pair<int, int>> & ones, int startIndx, int mov, vector<vector<int>> & grid){\n int sz = zeros.size(), szO = ones.size();\n if(sz == startIndx){\n minMovs = min(minMovs, mov);\n return;\n }\n auto &pr1 = zeros[startIndx];\n for(int indx = 0; indx < szO; indx++){\n auto &pr = ones[indx];\n if(grid[pr.first][pr.second] > 1){\n grid[pr.first][pr.second]--;\n findMoves(zeros, ones, startIndx+1, mov + abs(pr1.first - pr.first) + abs(pr.second - pr1.second), grid);\n grid[pr.first][pr.second]++;\n }\n }\n }\n};\n```\nJava\n```\nclass Solution {\n private int minMovs = -1;\n public int minimumMoves(int[][] grid) {\n minMovs = Integer.MAX_VALUE;\n int rows = grid.length, cols = grid[0].length;\n List<Pair<Integer, Integer>> zeros = new ArrayList<>(), ones = new ArrayList<>();\n for(int r = 0; r<rows; r++){\n for(int c = 0; c < cols; c++){\n if(grid[r][c] > 1){\n ones.add(new Pair<Integer, Integer>(r, c));\n }else if(grid[r][c] == 0){\n zeros.add(new Pair<Integer, Integer>(r, c));\n }\n }\n }\n findMoves(zeros, ones, 0, 0, grid);\n return minMovs;\n }\n private void findMoves(List<Pair<Integer, Integer>> zeros, List<Pair<Integer, Integer>> ones, int startIndx, int mov, int[][] grid){\n int sz = zeros.size(), szO = ones.size();\n if(sz == startIndx){\n minMovs = Math.min(minMovs, mov);\n return;\n }\n var pr1 = zeros.get(startIndx);\n for(int indx = 0; indx < szO; indx++){\n var pr = ones.get(indx);\n if(grid[pr.getKey()][pr.getValue()] > 1){\n grid[pr.getKey()][pr.getValue()]--;\n findMoves(zeros, ones, startIndx+1, mov + Math.abs(pr1.getKey() - pr.getKey()) + Math.abs(pr.getValue() - pr1.getValue()), grid);\n grid[pr.getKey()][pr.getValue()]++;\n }\n }\n }\n}\n``` | 4 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Python3, Permutations, Beats 100% | python3-permutations-beats-100-by-silvia-iwge | Intuition\nWe build two arrays: zeros to store indices of zeros in the grid, and d to store the indices we can use. If a cell can be used multiple times, we add | silvia42 | NORMAL | 2023-09-10T16:34:23.192738+00:00 | 2023-09-10T21:02:18.603761+00:00 | 709 | false | # Intuition\nWe build two arrays: `zeros` to store indices of zeros in the grid, and `d` to store the indices we can use. If a cell can be used multiple times, we add its indices to array `d` the corresponding number of times.\n\nWe evaluate all permutations, calculate the distances, and select the one with the smallest total distance.\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n zeros,d = [],[]\n for r in range(3):\n for c in range(3):\n if grid[r][c]==0:\n zeros.append((r,c))\n elif grid[r][c]>1:\n d+=[(r,c)]*(grid[r][c]-1)\n \n return min(sum(abs(R-r)+abs(C-c) for (r,c),(R,C) in zip(zeros,p)) for p in itertools.permutations(d))\n```\n# Improved Code - Beats 100% of Python solutions (Runtime and Memory)\nThank you **@Spaulding** for your suggestion!\n\nBecause array `d` contains duplicate elements, converting all permutations into a set eliminates duplicates and enhances runtime efficiency. However, this approach incurs the cost of storing all permutations in memory. Fortunately, this isn\'t a concern in this solution since we are dealing with a small array. `d` can contain a maximum of eight items.\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n zeros,d = [],[]\n for r in range(3):\n for c in range(3):\n if grid[r][c]==0:\n zeros.append((r,c))\n elif grid[r][c]>1:\n d+=[(r,c)]*(grid[r][c]-1)\n \n return min(sum(abs(R-r)+abs(C-c) for (r,c),(R,C) in zip(zeros,p)) for p in set(itertools.permutations(d)))\n```\n\n# Code explained in Python\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n answ,zeros,d = 100,[],[]\n for r in range(3):\n for c in range(3):\n if grid[r][c]==0:\n zeros.append((r,c))\n elif grid[r][c]>1:\n d+=[(r,c)]*(grid[r][c]-1)\n \n for p in itertools.permutations(d):\n actual=0 \n for (r,c),(R,C) in zip(zeros,p):\n actual+=abs(R-r)+abs(C-c)\n answ=min(answ,actual)\n \n return answ \n``` | 4 | 0 | ['Python3'] | 1 |
minimum-moves-to-spread-stones-over-grid | python3 backtracking - in neetcode.io codestyle | python3-backtracking-in-neetcodeio-codes-jhmn | Followed the same style of coding as done in neetcode.io series. Some might find this easy to follow.\n--\n# Code\n\nclass Solution:\n def minimumMoves(self, | t00rb0y | NORMAL | 2024-03-09T13:29:54.256667+00:00 | 2024-03-09T13:29:54.256689+00:00 | 138 | false | Followed the same style of coding as done in neetcode.io series. Some might find this easy to follow.\n--\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n \n ROWS = len(grid)\n COLS = len(grid[0])\n\n donors = {}\n zeros = set()\n for i in range(ROWS):\n for j in range(COLS):\n if grid[i][j] > 1:\n donors[(i,j)] = grid[i][j]\n elif grid[i][j] == 0:\n zeros.add((i,j))\n \n if not donors:\n return 0\n \n path_cost = []\n result = [float(\'inf\')]\n def backtrack():\n if len(zeros) == 0:\n cur_score = sum(path_cost)\n result[0] = min(result[0], cur_score)\n return\n \n for i,j in zeros.copy():\n for k, v in donors.items():\n if v > 1:\n idonor, jdonor = k\n cost = abs(i-idonor)+abs(j-jdonor)\n\n path_cost.append(cost)\n zeros.remove((i,j))\n donors[k] -= 1\n\n backtrack()\n\n path_cost.pop()\n zeros.add((i,j))\n donors[k] += 1\n\n backtrack()\n return result[0]\n``` | 3 | 0 | ['Backtracking', 'Python3'] | 1 |
minimum-moves-to-spread-stones-over-grid | Simple and clear python3 solution | 61 ms - faster than 92.33% solutions | simple-and-clear-python3-solution-61-ms-8bfbp | Complexity\n- Time complexity: O(m^n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\nwh | tigprog | NORMAL | 2023-10-27T20:04:15.483213+00:00 | 2023-10-27T20:04:15.483237+00:00 | 161 | false | # Complexity\n- Time complexity: $$O(m^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere (see code) `n = grid.length where ceil == 0`, `m = grid.length where ceil != (0 or 1)`\nNB, `max(n + m) = 9`, so the greatest value of $m^n$ is 1024.\n\n# Code\n``` python3 []\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n zeros = []\n more = []\n for i, line in enumerate(grid):\n for j, elem in enumerate(line):\n if elem == 0:\n zeros.append([i, j])\n elif elem != 1:\n more.append([i, j, elem - 1])\n\n n = len(zeros)\n m = len(more)\n\n def recursion(index):\n if index == n:\n return 0\n zero_i, zero_j = zeros[index]\n\n result = float(\'inf\')\n for k in range(m):\n i, j, elem = more[k]\n if elem != 0:\n more[k][2] -= 1\n current = (\n recursion(index + 1)\n + abs(i - zero_i)\n + abs(j - zero_j)\n )\n result = min(result, current)\n more[k][2] += 1\n return result\n \n return recursion(0)\n``` | 3 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Using Bit Mask DP easy solution | using-bit-mask-dp-easy-solution-by-maybk-5u75 | Intuition\nEasy Constraints\n\n# Approach\nBit Masks DP\n\n# Complexity\n- Time complexity:\nO(8x8x2^8)\n\n- Space complexity:\nO(8x8x2^8)\n\n# Code\n\nclass So | maybk | NORMAL | 2023-09-14T18:14:05.981324+00:00 | 2023-09-14T18:14:05.981353+00:00 | 455 | false | # Intuition\nEasy Constraints\n\n# Approach\nBit Masks DP\n\n# Complexity\n- Time complexity:\nO(8x8x2^8)\n\n- Space complexity:\nO(8x8x2^8)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n vector<pair<int,int>>can,need;\n int n=grid.size(),m=grid[0].size();\n for(int i=0;i<n;i++)for(int j=0;j<n;j++){\n while(grid[i][j]>1)can.push_back({i,j}),grid[i][j]--;\n if(!grid[i][j])need.push_back({i,j});\n }assert(can.size()==need.size());\n n=can.size();\n int mx=(1ll<<n);\n vector<vector<int>>dp(n+5,vector<int>(mx,1e8));\n dp[n][(1ll<<n)-1]=0;\n for(int i=n-1;i>=0;i--){\n for(int j=0;j<mx;j++){\n for(int k=0;k<n;k++){\n int mask=(1ll<<k);\n if(!(mask&j))dp[i][j]=min(dp[i][j],abs(can[i].first-need[k].first)+abs(can[i].second-need[k].second)+dp[i+1][j|(mask)]);\n }\n }\n }return dp[0][0];\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | 🔥Clean & Best C++ Code⭐ || 💯Recursion with BackTracking✅ | clean-best-c-code-recursion-with-backtra-uqqp | Code\n## Please Upvote if u found it useful\uD83E\uDD17\n\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n int mini = INT_ | aDish_21 | NORMAL | 2023-09-11T16:17:24.960200+00:00 | 2023-09-11T16:17:24.960225+00:00 | 99 | false | # Code\n## Please Upvote if u found it useful\uD83E\uDD17\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n int mini = INT_MAX;\n int cnt_0 = 0;\n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++)\n if(grid[i][j] == 0)\n cnt_0++;\n }\n if(!cnt_0)\n return 0;\n\n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){\n if(grid[i][j] == 0){\n for(int k = 0 ; k < 3 ; k++){\n for(int h = 0 ; h < 3 ; h++){\n if(grid[k][h] > 1){\n int x = abs(i - k) + abs(j - h);\n grid[k][h]--;\n grid[i][j] = 1;\n mini = min(mini, x + minimumMoves(grid));\n grid[k][h]++;\n grid[i][j] = 0;\n }\n }\n }\n }\n }\n }\n return mini;\n }\n};\n\n``` | 3 | 0 | ['Backtracking', 'Recursion', 'Matrix', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Python dfs solution | python-dfs-solution-by-lm105013-ae9c | Intuition\n Describe your first thoughts on how to solve this problem. \nExcess stones must go to a empty cell, find all blank and excess cells, and use dfs to | lm105013 | NORMAL | 2023-09-11T13:27:54.910962+00:00 | 2023-09-11T13:27:54.910983+00:00 | 195 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExcess stones must go to a empty cell, find all blank and excess cells, and use dfs to find the best way to move each stone\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n excess, blank = {}, []\n for i in range(3):\n for j in range(3):\n num = grid[i][j]\n if num == 1: continue\n elif num > 1: excess[(i, j)] = num\n else: blank.append((i, j))\n \n def dfs(i):\n if i == len(blank):\n return 0\n res = inf\n a, b = blank[i]\n for (x, y) in excess:\n if excess[(x, y)] == 1:\n continue\n excess[(x, y)] -= 1\n res = min(res, dfs(i+1) + abs(x-a) + abs(y-b))\n excess[(x, y)] += 1\n return res\n return dfs(0)\n``` | 3 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | [C++] Backtracking from the zero cells | c-backtracking-from-the-zero-cells-by-aw-rtb1 | Intuition\n Describe your first thoughts on how to solve this problem. \nTry all possible solutions to move stones to the cells without stone. \n\n# Approach\n | pepe-the-frog | NORMAL | 2023-09-11T11:43:18.827040+00:00 | 2023-09-11T11:43:18.827057+00:00 | 234 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry all possible solutions to move stones to the cells without stone. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Collect the cells without stone (`grid[r][c] == 0`)\n2. Try to grab a stone from the cell with more than one stone (`grid[r][c] > 1`)\n3. Try for each cell without stone using backtracking\n\n# Complexity\n- Time complexity: $$O((m * n)^{(m * n)})$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m * n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // time/space: O((mn)^(mn))/O(mn)\n int minimumMoves(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector<vector<int>> zeros;\n for (int r = 0; r < m; r++) {\n for (int c = 0; c < n; c++) {\n if (grid[r][c] == 0) zeros.push_back({r, c});\n }\n }\n\n int result = INT_MAX;\n helper(grid, zeros, 0, 0, result);\n return result;\n }\nprivate:\n void helper(vector<vector<int>>& grid, vector<vector<int>>& zeros, int i, int move, int& result) {\n // terminate\n if (i == zeros.size()) {\n result = min(result, move);\n return;\n }\n\n // enumerate\n int m = grid.size(), n = grid[0].size();\n for (int r = 0; r < m; r++) {\n for (int c = 0; c < n; c++) {\n if (grid[r][c] <= 1) continue;\n grid[r][c]--;\n int dr = abs(zeros[i][0] - r);\n int dc = abs(zeros[i][1] - c);\n helper(grid, zeros, i + 1, move + dr + dc, result);\n grid[r][c]++;\n }\n }\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | JavaScript - Backtracking - 55ms - O((#zero cells + 1)!) | javascript-backtracking-55ms-ozero-cells-tit0 | Intuition\nSolved it first using greedy approach. Failed.\n\n# Approach\nI had the list of cells with zeros and extras left over from the greedy approach, so th | justacoder3 | NORMAL | 2023-09-10T23:52:32.531856+00:00 | 2023-09-12T03:42:54.329507+00:00 | 245 | false | # Intuition\nSolved it first using greedy approach. Failed.\n\n# Approach\nI had the list of cells with zeros and extras left over from the greedy approach, so this led to a faster recursive backtracking approach than most other solutions.\n# Complexity\n- Time complexity:\nFor every zero cell we try getting one from all cells with extra, but as we recursively approach the last zero, there are only a few remaining extras. In other words we have #extra eggs and #zeros baskets and we try all combinations to see which requires the fewest moves. (this is really (#zero cells + 1)! since \'baskets\' and \'eggs\' have to be equal in number)\nO(#zeros * #extras!)\n- Space complexity:\nO(9) = O(1)\n\n# Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minimumMoves = function(grid) {\n let zeros = [];\n let extras = [];\n let ans = 0;\n for (let r = 0; r < 3; ++r) {\n for (let c = 0; c < 3; ++c) {\n if (grid[r][c] > 1) {\n extras.push([r,c, grid[r][c]]);\n } else if (grid[r][c] == 0) {\n zeros.push([r,c]);\n }\n }\n }\n function solve(index) {\n if (index >= zeros.length) {\n return 0;\n }\n let min = Number.MAX_SAFE_INTEGER; \n let [r, c] = zeros[index];\n for (let j = 0; j < extras.length; ++j) {\n if (extras[j][2] > 1) {\n extras[j][2] -= 1; \n min = Math.min(min, Math.abs(extras[j][0] - r) + Math.abs(extras[j][1] - c) + solve(index + 1));\n extras[j][2] += 1; \n }\n }\n return min;\n }\n return solve(0);\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
minimum-moves-to-spread-stones-over-grid | C++ Bit Masking DP Solution | c-bit-masking-dp-solution-by-dhavalkumar-ykok | Complexity\n- Time complexity: O(n.m.2 ^ {2m})\n\n- Space complexity: O(n.2 ^ m)\n\n\n# Code\n\nclass Solution {\npublic:\n int minimumMoves(vector<vector<in | dhavalkumar | NORMAL | 2023-09-10T07:06:48.825111+00:00 | 2023-09-11T18:24:35.786355+00:00 | 166 | false | # Complexity\n- Time complexity: $$O(n.m.2 ^ {2m})$$\n\n- Space complexity: $$O(n.2 ^ m)$$\n\n\n# Code\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n vector<vector<int>> has;\n vector<pair<int, int>> need;\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (grid[i][j] > 1) {\n has.push_back({i, j, grid[i][j] - 1});\n } else if (grid[i][j] == 0) {\n need.emplace_back(i, j);\n }\n }\n }\n\n int n = (int)has.size();\n int m = (int)need.size();\n int all_set = (1 << m) - 1;\n \n auto cost = [&](int x, int y, int mask) -> int {\n int tot = 0;\n for (int i = 0; i < m; i++) {\n if (mask & (1 << i)) {\n tot += abs(x - need[i].first) + abs(y - need[i].second);\n }\n }\n return tot;\n };\n \n vector<vector<int64_t>> dp(n + 1, vector<int64_t>(all_set + 1, -1));\n function<int64_t(int, int)> f = [&](int i, int mask) -> int64_t {\n if (all_set == mask)\n return 0;\n if (i == n) \n return INT_MAX;\n int64_t& ans = dp[i][mask];\n if (ans != -1)\n return ans;\n ans = INT_MAX;\n for (int bs = 1; bs <= all_set; bs++) {\n if ((mask & bs) == 0 and __builtin_popcount(bs) <= has[i][2]) {\n ans = min(ans, f(i + 1, mask | bs) + cost(has[i][0], has[i][1], bs));\n }\n }\n return ans;\n };\n return f(0, 0);\n }\n};\n```\n\n# Explanation\n \n1) Dynamic Programming Array (dp):\n\n- dp is a 2D array used for memoization. It has dimensions [n + 1][all_set + 1], where:\n - n is the number of cells with extra stones (i.e., the length of the has vector).\n - all_set is a bitmask representing all cells in the need vector. In this context, all_set is the state where all cells in need have been filled.\n- dp[i][mask] represents the minimum number of moves required to fill the cells in the need vector while considering the first i cells in the has vector and with the current state represented by the bitmask mask.\n\n2) DP Base Cases:\n\n- The base cases are critical to the DP recursion. They help terminate the recursion and provide a foundation for building the solution.\n- Two base cases are defined:\n - If mask covers all cells in the need vector (all_set == mask), it means all cells have been filled, and the function returns 0 because there are no more moves required.\n - If i reaches n (all cells with extra stones have been considered), but not all cells are filled (all_set != mask), it returns INT_MAX to indicate that this arrangement is not valid. This ensures that invalid states are assigned a very high cost.\n\n3) DP Recursion and Update:\n\n- The main DP recursion is implemented in the f function. It takes two parameters: i (the current cell being considered from the has vector) and mask (the current state of filling cells in the need vector).\n- Within the recursion, the code iterates through possible bitmasks bs that can be used to fill some of the cells in need.\n- It checks if bs can be used and if it hasn\'t been used before ((mask & bs) == 0). Additionally, it ensures that the number of stones in the cell represented by bs is less than or equal to the number of stones available in the current has cell.\n- If these conditions are met, it updates the ans by recursively calling the f function with the new state (mask | bs) and adds the cost of this arrangement (cost(has[i][0], has[i][1], bs)) to the current ans. It keeps track of the minimum ans among all valid arrangements.\n\n4) Return Value:\n\n- The final result, representing the minimum number of moves required to fill the grid, is stored in dp[0][0]. This value is returned as the solution to the problem. | 3 | 0 | ['Dynamic Programming', 'Bit Manipulation', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | Try all Possible permutation(i.e Atmost 3!)[O(1)] | try-all-possible-permutationie-atmost-3o-x0h9 | Intuition\nMy idea is that we can try all the possible permuation of number greater than 1 and we will get the moves required for each step by\n|x1-x2| + |y1-y2 | __Abcd__ | NORMAL | 2023-09-10T04:45:08.688311+00:00 | 2023-09-10T04:53:43.407865+00:00 | 367 | false | # Intuition\nMy idea is that we can try all the possible permuation of number greater than 1 and we will get the moves required for each step by\n|x1-x2| + |y1-y2|\nwill repeat it for all the permuations possible \nand then will get the answer... \n\n\n# Space complexity : \nSince i know array that i have created will store only atmost values\nso space complexity will be constant O(1)\n\n# Time complexity:\nIt will do atmost 9*9 operations in any for loop i have used \nso my time complexity will be constant O(1)\n# Code\n```\nclass Solution {\npublic:\n int helper(vector<vector<int>>& a1,vector<vector<int>>& a2,int curr = 0){\n for(int i = 0;i<a1.size();i++)\n curr+=abs(a1[i][0] - a2[i][0]) + abs(a1[i][1] - a2[i][1]);\n return curr;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n vector<vector<int>> arr1,arr2;\n for(int i= 0;i<3;i++){\n for(int j = 0;j<3;j++){\n if(grid[i][j] > 1){\n for(int start = 0;start < grid[i][j]-1;start++)\n arr1.push_back({i,j});\n }else if(!grid[i][j])arr2.push_back({i,j});\n }\n } \n int ans = helper(arr1,arr2);\n while(next_permutation(arr1.begin() , arr1.end()))\n ans = min(ans,helper(arr1,arr2));\n return ans;\n }\n};\n```\n\n\n# Let me know if have any kind of query regarding approach or through process used. | 3 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++ || Easy Understanding || BackTracking | c-easy-understanding-backtracking-by-n_i-1ow8 | Code\n\nclass Solution {\nprivate:\n bool check(vector<vector<int>> &grid){\n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){ | __SAI__NIVAS__ | NORMAL | 2023-09-10T04:35:39.618365+00:00 | 2023-09-10T04:35:39.618384+00:00 | 355 | false | # Code\n```\nclass Solution {\nprivate:\n bool check(vector<vector<int>> &grid){\n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){\n if(grid[i][j] != 1) return false;\n }\n }\n return true;\n }\n \n int helper(vector<vector<int>> &grid){\n if(check(grid)){\n return 0;\n }\n \n int answer = INT_MAX;\n \n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){\n if(grid[i][j] == 0){\n grid[i][j] = 1;\n \n for(int ii = 0 ; ii < 3 ; ii++){\n for(int jj = 0 ; jj < 3 ; jj++){\n if(grid[ii][jj] > 1){\n grid[ii][jj] -= 1;\n answer = min(answer, abs(ii - i) + abs(jj - j) + helper(grid));\n grid[ii][jj] += 1;\n }\n }\n }\n \n grid[i][j] = 0;\n }\n }\n }\n \n return answer;\n \n }\n \npublic:\n \n int minimumMoves(vector<vector<int>>& grid) {\n return helper(grid);\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | Simple Backtraking solution | simple-backtraking-solution-by-bhattpara-aw20 | \n# Code\n\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n // Base Case\n int t = 0;\n for (int i = 0; i < | bhattparaj1 | NORMAL | 2023-09-10T04:25:13.794162+00:00 | 2023-09-10T04:25:13.794181+00:00 | 115 | false | \n# Code\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n // Base Case\n int t = 0;\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (grid[i][j] == 0)\n t++;\n if (t == 0)\n return 0;\n \n int ans = INT_MAX; \n for(int i = 0; i < grid.size(); i++){\n for(int j = 0; j < grid[i].size(); j++){\n \n if(grid[i][j]==0){\n for(int l = 0; l < 3; l++){\n for(int k = 0; k < 3; k++){\n int d = abs(l-i) + abs(k-j);\n\n if(grid[l][k] > 1){\n grid[l][k]--;\n grid[i][j]++;\n ans = min(ans, d+minimumMoves(grid));\n grid[l][k]++;\n grid[i][j]--;\n }\n }\n }\n }\n\n\n }\n }\n return ans;\n }\n};\n``` | 3 | 1 | ['C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | Simple Solution || Easy to Understand | simple-solution-easy-to-understand-by-qb-7d4r | Intuition\nSince, problem size is small, we can check for each permutation of stones.\n\n# Approach\nArrange the grid with no stones in all possible permutation | calm_porcupine | NORMAL | 2023-09-10T04:20:10.216310+00:00 | 2023-09-10T04:20:10.216327+00:00 | 146 | false | # Intuition\nSince, problem size is small, we can check for each permutation of stones.\n\n# Approach\nArrange the grid with no stones in all possible permutations and satisfy the request with the grids with more than 1 stone.\n\n\n# Code\n```\nclass Solution {\npublic:\n int solve(map<pair<int, int>, int>more, vector<pair<int, int>>less)\n {\n //less --> vector of pair storing indexes of positions with no stones.\n // more --> map of pair storing storing indexes of positions with more than 1 stones and its frquency = stones -1\n int ans = 0;\n for(auto x : less)\n {\n int curr = INT_MAX;\n int a = x.first;\n int b = x.second;\n pair<int, int>taken;\n for(auto y : more)\n {\n if(y.second==0)\n continue;\n int c = y.first.first;\n int d = y.first.second;\n\n if(curr>((abs(a-c)+abs(b-d))))\n {\n curr = (abs(a-c)+abs(b-d));\n taken.first = c;\n taken.second = d;\n }\n \n }\n more[taken]--;\n ans+=curr; \n }\n return ans;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n map<pair<int, int>, int>more;\n vector<pair<int, int>>less;\n for(int i=0;i<3;i++)\n {\n for(int j = 0;j<3;j++)\n {\n if(grid[i][j]==0)\n {\n pair<int, int>p;\n p.first = i;\n p.second = j;\n less.push_back(p);\n }\n else if(grid[i][j]>1)\n {\n int d = grid[i][j]-1;\n for(int x = 1;x<=d;x++)\n {\n pair<int, int>p;\n p.first = i; \n p.second =j;\n more[p]++;\n }\n }\n }\n }\n int ans = INT_MAX;\n // Trying all possible permutations\n do {\n ans = min(ans, solve(more, less));\n } while (next_permutation(less.begin(), less.end()));\n return ans;\n }\n};\n``` | 3 | 0 | ['Backtracking', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | easy backtracking | easy-backtracking-by-shashank__11-kiih | \n# Intuition\nLooking at the constraints be can see that be can apply backtraking to it.\n# Approach\nWhen Ever be see a cell with 0 value we now try to find a | shashank__11 | NORMAL | 2023-09-10T04:05:07.753333+00:00 | 2023-09-10T05:57:09.442719+00:00 | 726 | false | \n# Intuition\nLooking at the constraints be can see that be can apply backtraking to it.\n# Approach\nWhen Ever be see a cell with 0 value we now try to find a cell in which there are more than one value so that be can take 1 from it and then continue with that cell\n\n# Code\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n // Base Case\n bool flag=true;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]!=1) flag=false;\n }\n }\n if(flag) return 0;\n int ans=INT_MAX;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n int k=0;\n if(grid[i][j]==0){\n for(int a=0;a<3;a++)\n {\n for(int b=0;b<3;b++){\n if(grid[a][b]>1){\n grid[a][b]--;\n grid[i][j]++;\n k+=abs(i-a);\n k+=abs(j-b);\n ans=min(ans,k+minimumMoves(grid));\n grid[a][b]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Backtracking', 'C++'] | 2 |
minimum-moves-to-spread-stones-over-grid | EASY Brute-Force: Manhattan-distance | easy-brute-force-manhattan-distance-by-z-fwkw | 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 | zedzogrind | NORMAL | 2023-09-10T04:04:26.325231+00:00 | 2023-09-10T04:04:26.325262+00:00 | 393 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n \n \n def manhattan_distance_2D(point1, point2):\n x1, y1 = point1\n x2, y2 = point2\n return abs(x1 - x2) + abs(y1 - y2)\n \n sources = []\n zeros = []\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 0:\n zeros.append([i, j])\n if grid[i][j] > 1:\n for _ in range(grid[i][j] - 1):\n sources.append([i, j])\n\n min_moves = inf\n\n for perm in permutations(sources, len(zeros)):\n total_distance = 0\n for i in range(len(zeros)):\n total_distance += manhattan_distance_2D(zeros[i], perm[i])\n min_moves = min(min_moves, total_distance)\n\n return min_moves\n\n \n \n \n``` | 3 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | easy short efficient solution | easy-short-efficient-solution-by-maveric-k3qf | cpp\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>&v) {\n int ans = INT_MAX;\n for(int i=0; i<3; ++i){\n for(int | maverick09 | NORMAL | 2023-09-10T04:01:34.710505+00:00 | 2023-09-10T04:47:33.016427+00:00 | 576 | false | ```cpp\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>&v) {\n int ans = INT_MAX;\n for(int i=0; i<3; ++i){\n for(int j=0; j<3; ++j){\n if(v[i][j]){\n continue;\n }\n for(int a=0; a<3; ++a){\n for(int b=0; b<3; ++b){\n if(v[a][b]<2){\n continue;\n }\n int res = abs(i-a)+abs(j-b);\n --v[a][b]; ++v[i][j];\n res+=minimumMoves(v);\n ++v[a][b]; --v[i][j];\n ans = min(ans, res);\n }\n }\n }\n }\n return (ans==INT_MAX?0:ans);\n }\n};\n``` | 3 | 0 | ['Recursion', 'C'] | 1 |
minimum-moves-to-spread-stones-over-grid | Python3 | Beats 90% | No external dependencies | python3-beats-90-no-external-dependencie-rc20 | IntuitionSee comments in the codeCode | simosound94 | NORMAL | 2025-03-15T12:42:19.728918+00:00 | 2025-03-15T12:42:19.728918+00:00 | 61 | false | # Intuition
See comments in the code
# Code
```python3 []
class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
"""
:type grid: List[List[int]]
:rtype: int
[[1,3,0],
[1,0,0],
[1,0,3]]
[(0,2), (1,1), (1,2), (2,1)]
[(0,1,0), (2,2,1)]
i=3
j=0
cost = 3
min_cost = inf
"""
def dist(p1, p2):
return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
min_cost = float('inf')
def _step(i, cost):
if i == len(empty_cells):
# All empty cells have been assigned, we are done.
nonlocal min_cost
min_cost = min(cost, min_cost)
return
if cost > min_cost:
# The current cost is already to high. We can stop.
return
for j in range(len(cells_excess)): # for every cell that has stones in excess
if cells_excess[j][-1] > 0: # if it has still stones in excess
cells_excess[j][-1] -= 1 # remove one stone
cost_after_assignment = cost+dist(empty_cells[i], cells_excess[j]) # add distance to total cost
_step(i+1, cost_after_assignment) # continue to assign the next empty cell
cells_excess[j][-1] += 1 # backtrack: once the step finishes, add the stone back to the cell
# List with location of empty cells
empty_cells = [(r,c) for r, row in enumerate(grid) for c, cell in enumerate(row) if cell ==0]
# List with location of cells with excess of stones (along with the number of stones in excess)
cells_excess = [[r,c, cell-1] for r, row in enumerate(grid) for c, cell in enumerate(row) if cell >1]
# Run one step to assign one stone to one empty cell
_step(0,0)
return min_cost
``` | 2 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Java Simple Backtracking that passed all test cases | java-simple-backtracking-that-passed-all-4r6y | \n\n# Code\n\npublic int minimumMoves(int[][] grid) {\n List<int[]> suppliers=new ArrayList<>();\n List<int[]> consumers=new ArrayList<>();\n | acthyy | NORMAL | 2024-03-16T06:48:41.912534+00:00 | 2024-03-16T06:48:41.912558+00:00 | 222 | false | \n\n# Code\n```\npublic int minimumMoves(int[][] grid) {\n List<int[]> suppliers=new ArrayList<>();\n List<int[]> consumers=new ArrayList<>();\n for(int i=0; i<grid.length; i++){\n for(int j=0; j<grid.length; j++){\n if(grid[i][j]==0){\n consumers.add(new int[]{i, j});\n }\n\n if(grid[i][j]>1){\n suppliers.add(new int[]{i, j});\n }\n }\n }\n\n return backtrack(grid, consumers, suppliers, 0);\n }\n\n private int backtrack(int[][] grid, List<int[]> consumers, List<int[]> suppliers, int index){\n if(index==consumers.size()){\n return 0;\n }\n\n int moves=Integer.MAX_VALUE;;\n int[] consumer=consumers.get(index);\n int i=consumer[0], j=consumer[1];\n for(int[] supplier:suppliers){\n int a=supplier[0], b=supplier[1];\n if(grid[a][b]==1){continue;}\n grid[a][b]--;\n moves=Math.min(moves, Math.abs(a-i)+Math.abs(b-j)+backtrack(grid, consumers, suppliers, index+1));\n grid[a][b]++;\n }\n\n return moves;\n }\n\n */\n}\n``` | 2 | 0 | ['Java'] | 3 |
minimum-moves-to-spread-stones-over-grid | [Python3] Python Backtracking w/ Hashmap | python3-python-backtracking-w-hashmap-by-dkvj | Problem Breakdown:\n- There\'s a 3x3 board where each cell has a number that representes how many stones it has \n- Some cells have 0 stones, others have non-ze | abhinavp246 | NORMAL | 2023-11-06T01:45:34.909053+00:00 | 2023-11-06T01:45:34.909069+00:00 | 68 | false | Problem Breakdown:\n- There\'s a 3x3 board where each cell has a number that representes how many stones it has \n- Some cells have 0 stones, others have non-zero stones \n- We need to find a way to move the stones from the non-zero cells to the zero cells that minimizes the total distance the stones are moved\n\nI was initially trying to find a greedy solution, or some method of using BFS since it guarantees the shortest path, but took the hint and decided to go with a backtracking approach. \n\nThings we need to figure out: \n- How do I calculate the "distance" a stone moves? \n\t- Since stones can only be moved to cells that share a border (i.e adjacent), we can use manhattan distance [abs(x2-x1) + abs(y2-y1)] as the distance metric.\n- How do I represent the state of the board every time I move a stone? \n\t- We can use a hasmap to keep the stone count of the inital cells that had a surplus number of stones (>1). These cells can no longer be used **once their count == 1**.\n\nTo make things easier: \n- Keep an array storing the positions of the "zero" cells \n\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int: \n rows = len(grid)\n cols = len(grid[0])\n zero, extra = [], {} #Track cells with 0 stones, and cells with extra stones (>1)\n \n for r in range(rows): \n for c in range(cols): \n if grid[r][c] == 0: \n zero.append((r,c)) \n \n elif grid[r][c] > 1: \n extra[(r,c)] = grid[r][c]\n \n\t\t # Track the current zero cell (i), the state of the board (extra), and the distance moved so far (d)\n def backtrack(i, extra, d):\n nonlocal res \n\t\t\t\n\t\t\t# All zero cells have a stone, so update res \n if i >= len(zero): \n res = min(res, d)\n return \n \n for val in extra: \n if extra[val] > 1: # Check if the cell still has more that one stone, otherwise we can\'t use it \n m = abs(val[0] - zero[i][0]) + abs(val[1] - zero[i][1]) # Manhattan distance (distance to move the stone to get it to the current 0 cell) \n extra[val] -= 1 # Use the stone \n backtrack(i+1, extra, d+m) # Go to the next state \n extra[val] += 1 # Add the stone back to be used with the next val in extra \n \n res = math.inf \n backtrack(0, extra, 0)\n return res \n \n``` | 2 | 0 | ['Backtracking', 'Python'] | 0 |
minimum-moves-to-spread-stones-over-grid | Java | Backtracking with Bitmask Memorization | java-backtracking-with-bitmask-memorizat-umdf | 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 | zenggq | NORMAL | 2023-10-05T14:31:49.428016+00:00 | 2023-10-05T14:44:56.479521+00:00 | 42 | 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$$O(k^2*2^k)$$. $$k$$ is the number of empty cells.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(k*2^k)$$. $$k$$ is the number of empty cells.\n\n# Code\n```\nclass Solution {\n public int minimumMoves(int[][] grid) {\n List<Integer> froms = new ArrayList<>(), tos = new ArrayList<>();\n for (int i = 0; i < 9; i++) {\n int r = i / 3, c = i % 3, val = grid[r][c];\n if (val == 0) {\n tos.add(i);\n } else if (val > 1) {\n for (int j = 1; j < val; j++) {\n froms.add(i);\n }\n }\n }\n int[][] dp = new int[froms.size()][1 << froms.size()]; \n for (int[] row : dp) {\n Arrays.fill(row, -1);\n }\n return dfs(dp, froms, tos, 0, 0);\n }\n\n int dfs(int[][] dp, List<Integer> froms, List<Integer> tos, int cur, int state) {\n if (cur == froms.size()) {\n return 0;\n }\n if (dp[cur][state] != -1) {\n return dp[cur][state];\n }\n int fr = froms.get(cur) / 3, fc = froms.get(cur) % 3;\n int res = Integer.MAX_VALUE;\n for (int i = 0; i < tos.size(); i++) {\n if (((state >> i) & 1) == 1) {\n continue;\n }\n int tr = tos.get(i) / 3, tc = tos.get(i) % 3;\n state += 1 << i;\n res = Math.min(res, dfs(dp, froms, tos, cur + 1, state) + Math.abs(fr - tr) + Math.abs(fc - tc));\n state -= 1 << i;\n } \n return dp[cur][state] = res;\n }\n}\n``` | 2 | 0 | ['Backtracking', 'Memoization', 'Bitmask', 'Java'] | 0 |
minimum-moves-to-spread-stones-over-grid | Python easy to understand | permutation & pruning | python-easy-to-understand-permutation-pr-10uj | Intuition\n Describe your first thoughts on how to solve this problem. \nStore coordinates of empty slots to a list, and coordinates of extra stones to a list. | icode999 | NORMAL | 2023-10-04T15:38:44.060699+00:00 | 2023-10-04T15:38:44.060723+00:00 | 206 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStore coordinates of empty slots to a list, and coordinates of extra stones to a list. All we need is to try different element-wise matching of the two lists.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate over the grid to save empty slots in list ```places```, and extra stones in list ```stones```\n2. Try all permutations for the list ```places```, for each permutation, obtain the element-wise distance to ```stones```, and mantain the minimum. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nGetting all permutations for the ```places``` list has a complexity of $$O(n!)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe created two lists, $$O(n^2)$$\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n stones = []\n places = []\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 0:\n places.append((i, j))\n elif grid[i][j] > 1:\n stones.extend([(i, j) for _ in range(grid[i][j]-1)])\n def dist(cord1, cord2):\n return abs(cord1[0]-cord2[0]) + abs(cord1[1]-cord2[1])\n self.min_move = float(\'inf\')\n def search(i):\n if i == len(places):\n d = sum([dist(st, pl) for st, pl in zip(stones, places)])\n self.min_move = min(self.min_move, d)\n for j in range(i, len(places)):\n places[j], places[i] = places[i], places[j]\n search(i+1)\n places[j], places[i] = places[i], places[j]\n search(0)\n return self.min_move\n\n \n```\n\n# Optimizing with Pruning\nThe intuition is that while iterating over all permutations, we maintain the distance ```d``` so far. If ```d``` is larger than the global minimum so far, we should stop exploring. \n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n stones = []\n places = []\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 0:\n places.append((i, j))\n elif grid[i][j] > 1:\n stones.extend([(i, j) for _ in range(grid[i][j]-1)])\n def dist(cord1, cord2):\n return abs(cord1[0]-cord2[0]) + abs(cord1[1]-cord2[1])\n self.min_move = float(\'inf\')\n def search(i, d):\n if d >= self.min_move:\n return\n if i == len(places):\n self.min_move = min(self.min_move, d)\n for j in range(i, len(places)):\n places[j], places[i] = places[i], places[j]\n search(i+1, d+dist(places[i], stones[i]))\n places[j], places[i] = places[i], places[j]\n search(0, 0)\n return self.min_move\n```\n\n | 2 | 0 | ['Python3'] | 1 |
minimum-moves-to-spread-stones-over-grid | Min cost flow O(F*m*n) - Successive shortest path - 4ms - Beats 100% | min-cost-flow-ofmn-successive-shortest-p-sm6p | Intuition\nThe problem can be thought of assigning the excess nodes to nodes with nothing. That is, squares on the grid[i][j] will haves excess of grid[i][j]-1 | mhayter1 | NORMAL | 2023-09-11T07:22:56.640451+00:00 | 2023-09-11T07:25:28.073431+00:00 | 48 | false | # Intuition\nThe problem can be thought of assigning the excess nodes to nodes with nothing. That is, squares on the grid[i][j] will haves excess of grid[i][j]-1 if grid[i][j]>=2.\n# Approach\nCreate a graph with edges from grid[i][j]>=2 to grid[i][j]==0 with capacity 1 and cost being the manhattan distance (abs(y1-y2)+abs(x1-x2)). \n\nCreate edges from the super-source to each node with excess (grid[i][j]>=2) with capacity grid[i][j]-1.\n\nCreate edges from each node with 0 (grid[i][j]==0) to a super-sink.\n\nRun a min cost flow algorithm from super source to super sink.\n\nMore about the algorithm can be found here: https://cp-algorithms.com/graph/min_cost_flow.html\n\n\n# Complexity\n- Time complexity:\nO(F*m*n) where \n-F is the flow\n-m is the number of edges\n-n is the number of nodes\n\n# Space complexity:\nO(n^2)\n\n# Code\n```\n//mhayter1\n\nauto f=[]{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n return 0;\n}();\n\nstruct Edge{\n int from, to, capacity, cost;\n};\n\nvector<vector<int>> adj, cost, capacity;\n\nconst int INF = 1e9;\n\nvoid shortest_paths(int n, int v0, vector<int>& d, vector<int>& p) {\n d.assign(n, INF);\n d[v0] = 0;\n vector<bool> inq(n, false);\n queue<int> q;\n q.push(v0);\n p.assign(n, -1);\n\n while (!q.empty()) {\n int u = q.front();\n q.pop();\n inq[u] = false;\n for (int v : adj[u]) {\n if (capacity[u][v] > 0 && d[v] > d[u] + cost[u][v]) {\n d[v] = d[u] + cost[u][v];\n p[v] = u;\n if (!inq[v]) {\n inq[v] = true;\n q.push(v);\n }\n }\n }\n }\n}\n\nint min_cost_flow(int N, vector<Edge> &edges, int K, int s, int t) {\n adj.assign(N, vector<int>());\n cost.assign(N, vector<int>(N, 0));\n capacity.assign(N, vector<int>(N, 0));\n for (Edge e : edges) {\n adj[e.from].push_back(e.to);\n adj[e.to].push_back(e.from);\n cost[e.from][e.to] = e.cost;\n cost[e.to][e.from] = -e.cost;\n capacity[e.from][e.to] = e.capacity;\n }\n\n int flow = 0;\n int cost = 0;\n vector<int> d, p;\n while (flow < K) {\n shortest_paths(N, s, d, p);\n if (d[t] == INF)\n break;\n\n // find max flow on that path\n int f = K - flow;\n int cur = t;\n while (cur != s) {\n f = min(f, capacity[p[cur]][cur]);\n cur = p[cur];\n }\n\n // apply flow\n flow += f;\n cost += f * d[t];\n cur = t;\n while (cur != s) {\n capacity[p[cur]][cur] -= f;\n capacity[cur][p[cur]] += f;\n cur = p[cur];\n }\n }\n\n \n return cost;\n}\nclass Solution {\npublic:\n int nrows,ncols;\n \n int minimumMoves(vector<vector<int>>& grid) {\n nrows = grid.size();\n ncols = grid[0].size();\n \n vector<pair<int,int>> zeros, bigs;\n \n for(int i=0;i<nrows;i++) {\n for(int j=0;j<ncols;j++) {\n if (grid[i][j]==0) {\n zeros.push_back({i,j});\n }else if (grid[i][j]>=2) {\n bigs.push_back({i,j}); \n }\n }\n }\n \n int tot_nodes = nrows*ncols+2;\n //flow from zeros to bigs\n vector<Edge> edges;\n for(auto &[zy,zx]:zeros) {\n int zind = zy*ncols+zx;\n for(auto &[by,bx]:bigs) {\n int bind = by*ncols+bx;\n int cap = 1;\n int cost = abs(zy-by)+abs(zx-bx);\n edges.push_back({bind,zind,cap,cost});\n }\n }\n int source = tot_nodes-2;\n int sink = tot_nodes-1;\n\n for(auto &[by,bx]:bigs) {\n int bind = by*ncols+bx;\n edges.push_back({source,bind,grid[by][bx]-1,0});\n }\n \n for(auto &[zy,zx]:zeros) {\n int zind = zy*ncols+zx;\n edges.push_back({zind,sink,1,0});\n }\n return min_cost_flow(tot_nodes, edges,INF,source,sink);\n }\n};\n``` | 2 | 0 | ['Shortest Path', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Easy✅ || Beginner friendly || DFS || Recursion || Backtracking || C++ | easy-beginner-friendly-dfs-recursion-bac-9l29 | Explanation\nBFS wont work, since we are required to find out all possible ways and pick up the minimum moves possible\n\n- Now for every zero th cell we need t | freakieee | NORMAL | 2023-09-10T11:58:27.844337+00:00 | 2023-09-10T11:58:27.844364+00:00 | 141 | false | # Explanation\nBFS wont work, since we are required to find out all possible ways and pick up the minimum moves possible\n\n- Now for every zero th cell we need to try out every extra cell(the cell whose value is > 1) \n- First we will traverse the grid and store the positions of zero th and extra cell in 2 separate vectors\n- If my zeros vector is empty that indicates all cells are filled so we can return 0\n- Coming to solve method\n- We will traverse zeros vector and for every zeroth cell we will try to take 1 from every extra cell thats why I used a for loop on extras vector in solve method\n- We can pick up one from cell if thats value is > 1, so I will decrease its value by 1 and everytime I will take the minimum value among ans,abs(zeros[i].first-x)+abs(zeros[i].second-y)+solve(i+1,zeros,extras,grid)\n- After coming back I will increment my extra cell again(**Backtracking step**)\n\n# Code\n```\nclass Solution {\npublic:\n \n int solve(int i,vector<pair<int,int>> zeros,vector<pair<int,int>> extras,vector<vector<int>> grid)\n {\n if(i>=zeros.size())return 0;\n \n int ans=INT_MAX;\n for(int j=0;j<extras.size();j++)\n {\n int x=extras[j].first,y=extras[j].second;\n if(grid[x][y]>1)\n {\n grid[x][y]--;\n ans=min(ans,abs(zeros[i].first-x)+abs(zeros[i].second-y)+solve(i+1,zeros,extras,grid));\n grid[x][y]++;\n }\n }\n return ans;\n }\n \n int minimumMoves(vector<vector<int>>& grid) {\n vector<pair<int,int>> zeros,extras;\n for(int i=0;i<3;i++)\n {\n for(int j=0;j<3;j++)\n {\n if(grid[i][j]==0)zeros.push_back({i,j});\n if(grid[i][j]>1)extras.push_back({i,j});\n }\n }\n \n if(zeros.size()==0)return 0;\n return solve(0,zeros,extras,grid);\n }\n};\n``` | 2 | 0 | ['Backtracking', 'Depth-First Search', 'Recursion', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | C++/Python, backtracking/bitmask dp solution with explanation | cpython-backtrackingbitmask-dp-solution-ejghv | backtracking (permutation)\nif there are m cells whose number of stone is 0,\nthere are also m stones on different cells whose number of stone > 1.\nSo, use bac | shun6096tw | NORMAL | 2023-09-10T10:42:46.725289+00:00 | 2023-09-10T11:35:44.999873+00:00 | 158 | false | ### backtracking (permutation)\nif there are m cells whose number of stone is 0,\nthere are also m stones on different cells whose number of stone > 1.\nSo, use backtracking to list permutation of stone to find the minimum cost.\ne.g., there are some stone at [(0,0), (0,1)], there are some cells need a stone [(2,2), (1,2)]\nwe have \n(0,0) -> (2,2), (0,1) -> (1,2)\n(0,0) -> (1,2), (0,1) -> (2,2)\nIn implementation, we can list permutation of coordinate where need a stone.\n\ntc is O(mn\u22C5(mn)!), sc is O(m+n).\n### python\n```python\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n p0 = []\n p1 = []\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n p0.append((i, j))\n for _ in range(1, grid[i][j]):\n p1.append((i, j))\n if not p0 and not p1: return 0\n ans = inf\n backtrack_0 = []\n\n def dfs(used0):\n if len(backtrack_0) == len(p0):\n nonlocal ans\n sub = 0\n for (x1, y1), (x2, y2) in zip(backtrack_0, p1):\n sub += abs(x2 - x1) + abs(y2 - y1)\n if sub < ans: ans = sub\n return\n \n for i in range(len(p0)):\n if used0 >> i & 1: continue\n backtrack_0.append(p0[i])\n dfs(used0 | (1 << i))\n backtrack_0.pop()\n dfs(0)\n return ans\n```\n### c++\n```cpp\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n vector<pair<int, int>> p0, p1;\n for (int i = 0; i < 3; i += 1) {\n for (int j = 0; j < 3; j += 1) {\n for (int k = 1; k < grid[i][j]; k+=1) p1.emplace_back(i, j);\n if (grid[i][j] == 0) p0.emplace_back(i, j);\n }\n }\n if (p0.empty() && p1.empty()) return 0;\n int ans = INT_MAX;\n vector<pair<int, int>> backtrack_0;\n function<void(int)> dfs = [&] (int used_0) {\n if (backtrack_0.size() == p0.size()) {\n int sub = 0;\n for (int i = 0; i < p0.size(); i+=1)\n sub += abs(backtrack_0[i].first - p1[i].first) + abs(backtrack_0[i].second - p1[i].second);\n if (sub < ans) ans = sub;\n return;\n }\n for (int i = 0; i < p0.size(); i+=1) {\n if (used_0 >> i & 1) continue;\n backtrack_0.emplace_back(p0[i]);\n dfs(used_0 | (1 << i));\n backtrack_0.pop_back();\n }\n };\n dfs(0);\n return ans;\n }\n};\n```\n\n### dynamic programming - bitmask dp\np0 is positions where number of stone is 0.\np1 is positions where number of stone > 1, and has duplicate position, each position is a stone.\n\ndp[mask] means min cost to match p0, a bit of 1 in mask means matched.\ncnt is number of 1 bit in mask.\nAnd we enumerate each 1 bit to match cnt th position of p1.\ndp[mask] = min(dp[mask], dp[mask ^ (1 << j)] + cost(p0[j], p1[cnt-1])).\n\ntc is O(9 * 2^9), sc is (2^9).\n\n### python\n```python\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n p0 = []\n p1 = []\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n p0.append((i, j))\n for _ in range(1, grid[i][j]):\n p1.append((i, j))\n size = len(p0)\n def cost(x, y):\n return abs(x[0] - y[0]) + abs(x[1] - y[1])\n\n dp = [0] * (1 << size)\n for i in range(1, 1 << size):\n cnt = 0\n dp[i] = inf\n for j in range(size): cnt += i >> j & 1\n for j in range(size):\n if i >> j & 1:\n dp[i] = min(dp[i], dp[i ^ (1 << j)] + cost(p0[j], p1[cnt-1]))\n return dp[-1]\n```\n\n### c++\n```cpp\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n vector<pair<int, int>> p0, p1;\n for (int i = 0; i < 3; i += 1) {\n for (int j = 0; j < 3; j += 1) {\n for (int k = 1; k < grid[i][j]; k+=1) p1.emplace_back(i, j);\n if (grid[i][j] == 0) p0.emplace_back(i, j);\n }\n }\n if (p0.empty() && p1.empty()) return 0;\n auto cost = [] (pair<int, int>& x, pair<int, int>& y) -> int {\n return abs(x.first - y.first) + abs(x.second - y.second);\n };\n int size = p0.size();\n vector<int> dp (1 << size);\n for (int mask = 1; mask < 1 << size; mask += 1) {\n int cnt = 0;\n dp[mask] = INT_MAX;\n for (int j = 0; j < size; j+=1) cnt += mask >> j & 1;\n for (int j = 0; j < size; j+=1) {\n if (mask >> j & 1)\n dp[mask] = min(dp[mask], dp[mask ^ (1 << j)] + cost(p0[j], p1[cnt-1]));\n }\n }\n \n return dp[(1 << size) - 1];\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Backtracking', 'Depth-First Search', 'C', 'Python'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++ | Beats 100% | Easy to Understand | Recursive Solution | c-beats-100-easy-to-understand-recursive-zxk7 | 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 | charucjoshi | NORMAL | 2023-09-10T09:42:19.371490+00:00 | 2023-09-10T09:42:19.371508+00:00 | 50 | 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 n,m;\n int f(int ind, vector<vector<int>> &v0, vector<vector<int>> &v1, vector<vector<int>> &grid){\n if(ind == v0.size()) return 0;\n \n int ans = INT_MAX;\n for(int i = 0; i < v1.size(); ++i){\n int r = v1[i][0], c = v1[i][1];\n if(grid[r][c] > 1){\n grid[r][c]--;\n ans = min(ans, abs(r-v0[ind][0]) + abs(c-v0[ind][1]) + f(ind+1, v0, v1, grid));\n grid[r][c]++;\n } \n }\n return ans;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n n = grid.size(), m = grid[0].size();\n vector<vector<int>> v0, v1;\n for(int i = 0; i < n; ++i){\n for(int j =0; j < m; ++j){\n if(grid[i][j] == 0) v0.push_back({i,j});\n if(grid[i][j] > 1) v1.push_back({i,j});\n }\n }\n return f(0,v0,v1,grid);\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Backtracking C++ solution || Well commented and explained | backtracking-c-solution-well-commented-a-5e2e | Intuition\nConstraints are very less so we can just try every possible combination.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\ | anonymouss_01 | NORMAL | 2023-09-10T08:44:16.622499+00:00 | 2023-09-10T08:44:16.622518+00:00 | 163 | false | # Intuition\nConstraints are very less so we can just try every possible combination.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nStore the pos with 0 in v1 and for greater than 1 in v2. Then try all possible combinations of pair formed and return the minimum distance.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N!)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n // use backtracking to make every possible combination of pairs and calculate min distance among them\n int solve(vector<pair<int,int>>& v1, vector<pair<int,int>>& v2, int i){\n\n if(i>=v1.size()){\n return 0;\n }\n\n int ans=INT_MAX, inc=0;\n for(int j=0 ; j<v2.size() ; j++){\n \n int x=abs(v1[i].first-v2[j].first)+abs(v1[i].second-v2[j].second); // calculate min distance between two pairs \n int a=v2[j].first, b=v2[j].second;\n v2[j]={1e8,1e8}; // make it a big number so that it will not include in ans again\n \n inc=x+solve(v1,v2,i+1); // recursively solve for other cases\n ans=min(ans, inc); // store min\n\n v2[j]={a,b}; // backtrack and make it original again\n\n }\n\n return ans;\n }\n\n int minimumMoves(vector<vector<int>>& grid) {\n\n if (grid[0][0]==9 || grid[0][2]==9 || grid[2][0]==9 || grid[2][2]==9) return 18;\n if (grid[0][1]==9 || grid[1][0]==9 || grid[1][2]==9 || grid[2][1]==9) return 15;\n if (grid[1][1]==9) return 12; \n\n\n int n=grid.size(), m=grid[0].size();\n vector<pair<int,int>> v1,v2;\n\n for(int i=0 ; i<n ; i++){\n\n for(int j=0 ; j<m ; j++){\n\n if(grid[i][j]==0){ // if zero we have to club it with some pos with greater than 1 number\n v1.push_back({i,j});\n }\n\n else if(grid[i][j]>1){ // if greater than 1 we have to use it grid[i][j]-1 times with zeroes\n int x=grid[i][j]-1;\n while(x--){\n v2.push_back({i,j});\n }\n }\n\n }\n }\n\n int ans=solve(v1,v2,0);\n return ans;\n\n }\n};\n``` | 2 | 0 | ['Math', 'Backtracking', 'Recursion', 'Matrix', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Fairly Simple Backtracking Solution✅|| with Intuition and Comments📚 | fairly-simple-backtracking-solution-with-5aj3 | Intuition\nEach of the surplus stones can go to any vacant spot in the grid. So do just that! Transfer one of the extra stones (say John) to one of the vacant s | neil_paul | NORMAL | 2023-09-10T07:07:08.557937+00:00 | 2023-09-10T07:12:51.225837+00:00 | 298 | false | # Intuition\nEach of the surplus stones can go to any vacant spot in the grid. So do just that! Transfer one of the extra stones (say John) to one of the vacant spots (say McClane) and make a recursive call for the reamining stones. After all cells have one stone each, come back and fix John stone in any other vacant spot (say Simon) and repeat. Classic backtracking.\n\n# Complexity\n- Time complexity: O(N!)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) - for recursive stack\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nwhere N = number of cells with 0 stones.\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n m,n = 3,3\n self.res = math.inf\n vacant = [] # to store cell indices that have 0 stones\n extra = [] # cell indices with surplus stones\n #populate \'vacant\' and \'extra\' lists\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n vacant.append((i,j))\n elif grid[i][j]>1:\n for t in range(1,grid[i][j]): #store as many instances of a cell as many surplus stones\n extra.append((i,j))\n # Note: size of \'vacant\' and \'extra\' lists would be the same\n self.bt(0,extra,vacant,0,set())\n if not vacant: #if all cells have exactly one stone\n return 0\n return self.res\n\n def bt(self,i,extra,vacant,moves,vis):\n if i==len(extra): #compare and store ans, when leaf node is hit, ie, no cell has surplus stone\n self.res = min(self.res,moves)\n return\n \n # Intuitively, sending current surplus stone - stone[i] to each of the vacant positions one by one.\n for k in range(len(vacant)):\n if k not in vis:\n sendto = vacant[k]\n vis.add(k) #the visited set to store the cells that were in \'vacant\' list but now have been occupied\n m = abs(extra[i][0]-sendto[0])+abs(extra[i][1]-sendto[1]) #moves to send stone to vacant cell = manhattan distance\n self.bt(i+1,extra,vacant,moves+m,vis)\n vis.remove(k) #the ith stone has been removed from the vacant spot to make available for other stones.\n```\n\nFollow-up: I\'m sure there is a dp solution to this problem, but that is an overkill with these constraints. Might add that code also in future.\n\nPS. I\'m not sure about the time and space complexities. So any corrections/suggestions are welcome.\n\n\n# Drop a like, if you made it till here :D | 2 | 0 | ['Backtracking', 'Recursion', 'Matrix', 'Python3'] | 1 |
minimum-moves-to-spread-stones-over-grid | BFS + Permutations Detailed Explanation with well-commented Code | bfs-permutations-detailed-explanation-wi-pbqn | UPVOTE IF YOU LIKE \n# Intuition\n- The Intuition for this problem is bfs + trying all possible permutations.\n\n# Approach\n- We have to first find out which c | shaileshsingh23423 | NORMAL | 2023-09-10T04:55:58.319360+00:00 | 2023-09-10T04:58:10.059713+00:00 | 710 | false | # UPVOTE IF YOU LIKE \n# Intuition\n- The Intuition for this problem is bfs + trying all possible permutations.\n\n# Approach\n- We have to first find out which cell have more than 1 stone.\n- Now, suppose we have `3 cells` having more than 1 stone. Then, we have 6 choices from which cell we start and to which cell we go then.\n - For Ex : `[{1,2},{0,3},{3,3}]` has these permutations :-\n - `[{1,2},{0,3},{3,3}]`\n - `[{1,2},{3,3},{0,3}]`\n - `[{0,3},{1,2},{3,3}]`\n - `[{0,3},{3,3},{1,2}]`\n - ` [{3,3},{1,2},{0,3}]`\n - `[{3,3},{0,3},{1,2}]`\n- Now, We can move in four different directions. We will find all permutations of these directions. \n- Now, using `bfs` we will find `minimum moves` according to all the `permutations and combinations`. \n\n# Complexity\n- Time complexity: `O(24 * 24 * N * N)` here `N == 3`\n - Here, at most 4 cells can have `2 or more stones`. `Permuations = 24`\n - We have 4 directions, in which we can move. `Permutations = 24`\n - And, we have `bfs` which will take `N*N` complexity\n - Hence, `Total Time Complexity = O(24*24*N*N)`\n - `Note` : I have neglected complexity of finding permutations. It will be `O(4!)` in both cases.\n\n# Code\n```\nclass Solution {\nprivate:\n /* Finding Out All Permutation */\n void permutations(vector<pair<int,int>> &nums, int i, vector<vector<pair<int,int>>> &res) {\n if(i == nums.size()-1) {\n res.push_back(nums);\n return;\n }\n for(int k=i; k<nums.size(); k++) {\n swap(nums[k],nums[i]);\n permutations(nums,i+1,res);\n swap(nums[k],nums[i]);\n }\n }\n \n /* BFS to find min moves of the stones */\n int bfs(vector<vector<int>> &grid, int i, int j, vector<pair<int,int>> &movements) {\n int moves = 0;\n queue<pair<int,int>> q;\n q.push({i,j});\n int steps = 0;\n\n int dr[4];\n int dc[4];\n for(int k=0; k<4; k++) {\n dr[k] = movements[k].first;\n dc[k] = movements[k].second;\n }\n\n while(grid[i][j] != 1) {\n int size = q.size();\n steps++;\n while(size--) {\n auto it = q.front();\n q.pop();\n int row = it.first;\n int col = it.second;\n if(grid[row][col] == 0) {\n grid[i][j]--;\n grid[row][col] = 1;\n moves += steps-1;\n if(grid[i][j] == 1) break;\n }\n for(int k=0; k<4; k++) {\n int nrow = row+dr[k];\n int ncol = col+dc[k];\n if(nrow >= 0 && nrow < 3 && ncol >= 0 && ncol < 3) {\n q.push({nrow,ncol});\n }\n }\n }\n }\n return moves;\n }\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n int ans = 100;\n // Storing all cells in v which have more than 1 stone\n vector<pair<int,int>> v;\n for(int i=0; i<3; i++) {\n for(int j=0; j<3; j++) {\n if(grid[i][j] > 1) {\n v.push_back({i,j});\n }\n }\n }\n \n /* Finding all permutations for the cell having stones more than 1 */\n vector<vector<pair<int,int>>> stonePer;\n permutations(v,0,stonePer);\n \n /* Finding all permutations for the order of movements in cell */\n vector<vector<pair<int,int>>> moveDirections;\n vector<pair<int,int>> movements = {{-1,0},{1,0},{0,1},{0,-1}};\n permutations(movements,0,moveDirections);\n \n /* Finding the minimum answer according to all permutations using bfs */\n for(int i=0; i<stonePer.size(); i++) { \n for(int k=0; k<moveDirections.size(); k++) { // Loop for movement Direction Permutations\n movements = moveDirections[k];\n vector<vector<int>> dupGrid = grid;\n int currAns = 0;\n for(int j=0; j<stonePer[i].size(); j++) {\n int row = stonePer[i][j].first;\n int col = stonePer[i][j].second;\n currAns += bfs(dupGrid,row,col,movements);\n }\n ans = min(ans,currAns);\n }\n }\n \n return ans;\n }\n};\n```\n# UPVOTE IF YOU LIKE | 2 | 0 | ['Backtracking', 'Breadth-First Search', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | BFS || Fast | bfs-fast-by-lil_toeturtle-2bri | \nclass Solution {\n int[] dir={-1, 0, 1, 0, -1};\n public int minimumMoves(int[][] grid) {\n HashSet<String> vis=new HashSet<>();\n int l=0 | Lil_ToeTurtle | NORMAL | 2023-09-10T04:43:09.190526+00:00 | 2023-09-10T04:43:09.190545+00:00 | 826 | false | ```\nclass Solution {\n int[] dir={-1, 0, 1, 0, -1};\n public int minimumMoves(int[][] grid) {\n HashSet<String> vis=new HashSet<>();\n int l=0;\n Queue<int[][]> q = new LinkedList<>();\n q.add(grid);\n q.add(null);\n while(!q.isEmpty()) {\n int[][] g=q.poll();\n if(g==null){\n l++;\n if(!q.isEmpty()){\n q.add(null);\n }else break;\n }else{\n if(isRes(g)) return l;\n f(g, q, vis);\n }\n }\n return -1;\n }\n boolean isRes(int[][] g){\n for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(g[i][j]!=1) return false;\n return true;\n }\n void f(int[][] grid, Queue<int[][]> q, HashSet<String> vis) {\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0){\n for(int k=0;k<4;k++){\n int x=dir[k]+i, y=dir[k+1]+j;\n if(x>=0 && x<3 && y>=0 && y<3){\n if(grid[x][y]>0){\n int[][] g=new int[3][3];\n for(int ii=0;ii<3;ii++) for(int jj=0;jj<3;jj++) g[ii][jj]=grid[ii][jj];\n g[i][j]=1;\n g[x][y]-=1;\n String s=stringify(g);\n if(!vis.contains(s)){\n q.add(g);\n vis.add(s);\n }\n }\n }\n }\n }\n }\n }\n }\n String stringify(int[][] g) {\n char[] ch=new char[9];\n int ind=0;\n for(int i=0;i<3;i++) for(int j=0;j<3;j++) ch[ind++]=(char)(g[i][j]-\'1\');\n return new String(ch);\n }\n}\n``` | 2 | 1 | ['Breadth-First Search', 'Java'] | 1 |
minimum-moves-to-spread-stones-over-grid | [C++] l Brute Force l Recursion | c-l-brute-force-l-recursion-by-vineet-0-1ots | Intution\nBrute Force\n\n\n\n\nTry all possiblities\n\n# Approach\njust using Brute Force\n\n\n\n\n\n\n# Code\n\nclass Solution {\n vector<vector<int>> check | Vineet-0 | NORMAL | 2023-09-10T04:36:42.248111+00:00 | 2023-09-10T04:36:42.248143+00:00 | 110 | false | # Intution\nBrute Force\n\n\n\n\nTry all possiblities\n\n# Approach\njust using Brute Force\n\n\n\n\n\n\n# Code\n```\nclass Solution {\n vector<vector<int>> check = {{1,1,1},{1,1,1},{1,1,1}};\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n if(grid==check)\n return 0;\n int ans = INT_MAX;\n for(int i = 0;i<3;i++)\n {\n for(int j = 0; j<3;j++)\n {\n for(int k = 0 ; k<3;k++)\n {\n for(int l = 0;l<3;l++)\n {\n if(grid[i][j]==0 && grid[k][l]>1)\n {\n grid[i][j]++;\n grid[k][l]--;\n ans = min(ans,abs(i-k)+abs(j-l)+minimumMoves(grid));\n grid[i][j]--;\n grid[k][l]++;\n }\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Recursion', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Brute Force Solution with desi jugaad (i-var) | brute-force-solution-with-desi-jugaad-i-lwa8i | # Intuition \n\n\n# Approach\n\nFor every cell containing ZERO find the cell with value more than ONE with minimum manhatan distance, as this is a greedy way | i-var | NORMAL | 2023-09-10T04:31:02.616608+00:00 | 2023-09-10T04:31:02.616638+00:00 | 46 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor every cell containing ZERO find the cell with value more than ONE with minimum manhatan distance, as this is a greedy way of selecting the contributor cell for cell with value ZERO so we will do same with 4 different versions of the matrix each with 90 degree rotation of previous. Find the minimum of all the answers.\n\n\n# Code\n``` C++ []\nclass Solution {\n \n void rotate(vector<vector<int>>& m, int x, int y){\n int temp1, temp2;\n for(int i=x, j=0;i<y;i++,j++){\n temp1 = m[x][i];\n temp2 = m[i][y];\n m[i][y] = temp1;\n\n temp1 = temp2;\n temp2 = m[y][y-j];\n m[y][y-j] = temp1;\n\n temp1 = temp2;\n temp2 = m[y-j][x];\n m[y-j][x] = temp1;\n\n m[x][i] = temp2;\n }\n }\n \n \n int minMoves(vector<vector<int>> grid){\n vector<pair<int,int>> zeros, bigNum;\n for(int i=1;i<=3;i++){\n for(int j=1;j<=3;j++){\n if(grid[i-1][j-1]==0){\n zeros.push_back({i,j});\n }else if(grid[i-1][j-1]>1){\n bigNum.push_back({i,j});\n }\n }\n }\n \n int ans=0;\n int dist;\n pair<int,int> p;\n for(auto zero:zeros){\n dist = INT_MAX;\n for(auto n:bigNum){\n int d = abs(n.first-zero.first) + abs(n.second-zero.second);\n if(grid[n.first-1][n.second-1]>1 && dist>d){\n dist = d;\n p = n;\n }\n }\n grid[p.first-1][p.second-1]--;\n ans+=dist; \n }\n \n return ans;\n }\n \npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n int ans = INT_MAX;\n ans = min(ans, minMoves(grid));\n rotate(grid, 0, 2);\n ans = min(ans, minMoves(grid));\n rotate(grid, 0, 2);\n ans = min(ans, minMoves(grid));\n rotate(grid, 0, 2);\n ans = min(ans, minMoves(grid));\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | Backtracking | backtracking-by-nitleet12-xudx | Intuition\n Describe your first thoughts on how to solve this problem. \nTransfer one stone from the cell having more than one stone to any empty cell. \nTry ea | nitleet12 | NORMAL | 2023-09-10T04:16:49.600588+00:00 | 2023-09-10T04:16:49.600611+00:00 | 201 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTransfer one stone from the cell having more than one stone to any empty cell. \nTry each way to transfer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBacktracking\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 minimumMoves(int[][] grid) {\n return solver(grid);\n }\n \n int solver(int [][]grid){\n int mini=(int)1e8;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]>1){\n for(int x=0;x<3;x++){\n for(int y=0;y<3;y++){\n int temp=(int)1e8;\n if(grid[x][y]==0){\n grid[i][j]-=1;\n grid[x][y]+=1;\n temp=Math.abs(x-i)+Math.abs(y-j)+solver(grid);\n grid[i][j]+=1;\n grid[x][y]-=1;\n }\n mini=Math.min(mini,temp);\n }\n }\n }\n }\n }\n return (mini==(int)1e8)?0:mini;\n }\n}\n``` | 2 | 1 | ['Backtracking', 'Recursion', 'Java'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++| Short and Concise Solution | c-short-and-concise-solution-by-coder348-e1vb | Code\n\nclass Solution {\npublic:\n int func(vector<vector<int>>& v){\n int ans = INT_MAX;\n for(int i=0; i<3; ++i){\n for(int j=0; | coder3484 | NORMAL | 2023-09-10T04:04:20.484684+00:00 | 2023-09-10T04:04:20.484708+00:00 | 1,294 | false | # Code\n```\nclass Solution {\npublic:\n int func(vector<vector<int>>& v){\n int ans = INT_MAX;\n for(int i=0; i<3; ++i){\n for(int j=0; j<3; ++j){\n if(v[i][j]) continue;\n for(int a=0; a<3; ++a){\n for(int b=0; b<3; ++b){\n if(v[a][b]<2){\n continue;\n }\n int res = abs(i-a)+abs(j-b);\n --v[a][b]; ++v[i][j];\n res+=func(v);\n ++v[a][b]; --v[i][j];\n ans = min(ans, res);\n }\n }\n }\n }\n return (ans == INT_MAX ? 0 : ans);\n }\n int minimumMoves(vector<vector<int>>&v) {\n return func(v);\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | 🚀 Easy C++ || Recursive || simple || | easy-c-recursive-simple-by-satenderrkuma-5tds | \n\n# Code\n\nclass Solution {\npublic:\n int solve(vector<pair<int,int>>& arr1 , vector<pair<int,int>>& arr2 , int ind ,vector<vector<int>>& grid ){\n | satenderrkumar11 | NORMAL | 2023-09-10T04:01:32.402217+00:00 | 2023-09-10T04:03:16.734994+00:00 | 126 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<pair<int,int>>& arr1 , vector<pair<int,int>>& arr2 , int ind ,vector<vector<int>>& grid ){\n if(ind == arr2.size())return 0;\n \n int res = INT_MAX;\n for(auto [i,j]:arr1){\n if(grid[i][j] > 1){\n int d = abs(i - arr2[ind].first) + abs(j- arr2[ind].second);\n grid[i][j] --;\n res = min(res, d+solve(arr1, arr2, ind+1, grid));\n grid[i][j] ++;\n }\n }\n \n return res;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n \n vector<pair<int,int>> arr1;\n vector<pair<int,int>> arr2;\n \n for(int i =0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j] >1 )arr1.push_back({i,j});\n if(grid[i][j] == 0 )arr2.push_back({i,j});\n }\n }\n \n return solve(arr1, arr2,0 ,grid);\n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Wow! Just go through all paths | wow-just-go-through-all-paths-by-war02_a-khqb | IntuitionInitially thought its simple BFS, then got some test cases which make me think broader,
We have to go throgh all possible paths and pick minimum one.Th | war02_abhishek | NORMAL | 2025-02-09T10:03:45.827608+00:00 | 2025-02-09T10:05:24.259985+00:00 | 76 | false | # Intuition
Initially thought its simple BFS, then got some test cases which make me think broader,
We have to go throgh all possible paths and pick minimum one.Though DP will work but unable to think DP states
So decided to build recursion solution first.
# Approach
First note all extra's(>1), their location in vector.when all my extra vector have all 1 it means we are done,all are set so thats my base case.
I am going throgh all possible paths.So for each zero i will consider all extras that are available.If extra[i]>1 ie available i will take that move forward,If i am not considering extra[i] and considering extra[i+1] i will regain extra[i] value since i am passing it by refence.
mark grid[i][j]=1 ie mark visited.Since we will chose atleast 1 extra among available ones.
# Complexity
- Time complexity:
Exponential TC-> m^n*(3*3)
- Space complexity:
0(n)
# Code
```cpp []
class Solution {
public:
long helper(vector<vector<int>>grid,vector<int>&extra,vector<pair<int,int>>loc){
int cnt=0;
for(auto it:extra) if(it==1) cnt++;
if(cnt==extra.size()) return 0;
long op=INT_MAX;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]==0){
grid[i][j]=1;
for(int k=0;k<extra.size();k++)
{
if(extra[k]>1){
extra[k]--;
op=min(op,abs(i-loc[k].first)+abs(j-loc[k].second)+helper(grid,extra,loc));
extra[k]++;
}
}
}
}
}
return op;
};
int minimumMoves(vector<vector<int>>& grid) {
vector<int>extra;
vector<pair<int,int>>loc;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(grid[i][j]>1){
extra.push_back(grid[i][j]);
loc.push_back({i,j});
}
}
}
int n=extra.size();
return helper(grid,extra,loc);
}
};
``` | 1 | 0 | ['Recursion', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Javascript Backtracking with memoization | javascript-backtracking-with-memoization-fwrq | \n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(2^N)\n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \nO(N) | vijay369 | NORMAL | 2024-02-26T07:35:52.203022+00:00 | 2024-02-26T07:35:52.203054+00:00 | 44 | false | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(2^N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minimumMoves = function(grid) {\n // Memo to retreive value from visited cells\n let memo = new Map();\n\n // Collect the cells which have 0 stones\n // Collect the cells which have more than 1 stone\n let extraStoneCellsArr = [], zeroStoneCellsArr = [];\n\n for (let r=0; r<grid.length; r++) {\n for (let c=0; c<grid[r].length; c++) {\n if (grid[r][c] > 1) {\n extraStoneCellsArr.push([r, c, grid[r][c]]);\n }\n if (grid[r][c] === 0) {\n zeroStoneCellsArr.push([r, c]);\n }\n }\n };\n\n // Get minimum # of moves\n // horizontally and vertically by calculating the \n // distance between the cells\n\n const calculateMinMoves = (index, extras) => {\n // Base case\n if (index >= zeroStoneCellsArr.length) return 0;\n\n let memoKey = index + \'-\' + extras;\n\n if (memo.has(memoKey)) {\n return memo.get(memoKey);\n }\n \n // iterate over extra stones array to calcuate\n // minimum number of moves\n let min = Number.MAX_SAFE_INTEGER;\n let [rowZero, colZero] = zeroStoneCellsArr[index];\n\n for (let j=0; j<extraStoneCellsArr.length; j++) {\n if (extraStoneCellsArr[j][2] > 1) {\n // decrement the count of cell which has \n // more than 1 stone\n extraStoneCellsArr[j][2] -= 1;\n // calculate moves and backtack\n const moves = Math.abs(extraStoneCellsArr[j][0] - rowZero) + Math.abs(extraStoneCellsArr[j][1] - colZero) \n + calculateMinMoves(index + 1, extraStoneCellsArr);\n min = Math.min(min, moves);\n extraStoneCellsArr[j][2] += 1;\n }\n }\n memo.set(memoKey, min);\n return min;\n }\n\n return calculateMinMoves(0, extraStoneCellsArr)\n\n};\n``` | 1 | 0 | ['Backtracking', 'Recursion', 'Memoization', 'JavaScript'] | 0 |
minimum-moves-to-spread-stones-over-grid | Easy C++ Solution || Beats 98% (Using Backtracking) ✅✅ | easy-c-solution-beats-98-using-backtrack-lq62 | Code\n\nclass Solution {\npublic:\n int helper(vector<vector<int>> &usez,vector<vector<int>> &usem,int i,int n){\n if(i>=n){\n return 0;\n | Abhi242 | NORMAL | 2024-02-24T09:56:04.403288+00:00 | 2024-02-24T09:56:04.403313+00:00 | 605 | false | # Code\n```\nclass Solution {\npublic:\n int helper(vector<vector<int>> &usez,vector<vector<int>> &usem,int i,int n){\n if(i>=n){\n return 0;\n }\n int ans=INT_MAX;\n for(int k=0;k<usem.size();k++){\n if(usem[k][2]>1){\n usem[k][2]--;\n ans=min(ans,abs(usez[i][0]-usem[k][0])+abs(usez[i][1]-usem[k][1])+helper(usez,usem,i+1,n));\n usem[k][2]++;\n }\n }\n return ans;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n vector<vector<int>> usez;\n vector<vector<int>> usem;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0){\n usez.push_back({i,j});\n }\n }\n }\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]>1){\n usem.push_back({i,j,grid[i][j]});\n }\n }\n }\n return helper(usez,usem,0,usez.size());\n }\n};\n``` | 1 | 0 | ['Backtracking', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | BFS Approach | bfs-approach-by-alireza_ghods-thl1 | Intuition\n\nBFS is particularly well-suited for finding the shortest path or the minimum number of moves to reach a goal because it explores all possible moves | alireza_ghods | NORMAL | 2024-02-12T07:10:51.796053+00:00 | 2024-02-12T07:10:51.796083+00:00 | 50 | false | # Intuition\n\nBFS is particularly well-suited for finding the shortest path or the minimum number of moves to reach a goal because it explores all possible moves at a given depth before moving on to the next depth. This ensures that the first time it reaches the goal state (one stone per cell), it has found the path with the minimum number of moves.\n\n# Approach\n1. Initial State: is a tuple of grid and the number of steps. In the inital state the number of steps = 0.\n\n2. Goal State: The goal is a grid configuration where each cell contains exactly one stone.\n\n3. Move Generation: For each state, generate all possible next states by moving one stone from any cell with more than one stone to any adjacent cell (horizontally or vertically) that is not already full.\n\n4. Visited States: Use a set to keep track of visited states to avoid cycles and redundant searches.\n\n5. Queue: Use a queue to store states along with their depth from the initial state. The depth represents the number of moves made from the initial state to the current state.\n\nBFS Loop:\n\nDequeue a state from the queue.\nIf it\'s the goal state, return the depth.\nOtherwise, generate all possible moves from this state, and for each move that hasn\'t been visited yet, enqueue the new state along with the updated depth.\n\n# Complexity\n- Time complexity: It is hard to determined it depends on the grid and number of moves.\n\n- Space complexity:It is hard to determined it depends on the grid and number of moves.\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n \n def get_state(g):\n return \'\'.join(str(cell) for row in g for cell in row)\n \n def move_stone(g, i, j, di, dj):\n # Create a new grid with the stone moved\n new_grid = [row[:] for row in g] # Shallow copy of each row\n new_grid[i][j] -= 1\n new_grid[i + di][j + dj] += 1\n return new_grid\n\n target = "111111111" # Target grid state as a string\n queue = deque([(grid, 0)]) # Tuple of (grid, move)\n visited = set([get_state(grid)])\n \n while queue:\n cur_grid, move = queue.popleft()\n cur_string = get_state(cur_grid)\n if cur_string == target: \n return move\n \n for i in range(3):\n for j in range(3):\n if cur_grid[i][j] > 1:\n for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n if 0 <= i + di < 3 and 0 <= j + dj < 3:\n next_grid = move_stone(cur_grid, i, j, di, dj)\n next_state = get_state(next_grid)\n if next_state not in visited:\n visited.add(next_state)\n queue.append((next_grid, move + 1))\n \n return -1 # Return -1 if no solution found\n\n\n``` | 1 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Permutation approach (50ms) | permutation-approach-50ms-by-deepanshus-8pw8 | Intuition\nEvery zero needs to borrow from some position. No need to traverse grid to match these two positions.\n# Approach\nCreate a list zeroes with of all c | deepanshus | NORMAL | 2024-01-17T16:38:15.544492+00:00 | 2024-01-17T16:38:15.544521+00:00 | 5 | false | # Intuition\nEvery zero needs to borrow from some position. No need to traverse grid to match these two positions.\n# Approach\nCreate a list `zeroes` with of all coordinates of all cells with value 0. Make another list `extras` for cells with value greater than 1. But create duplicate entries for each extra stone. \nFor e.g. if cell 0,0 has value 3, then add this cell to the list twice.\n\nCreate a vector the length of `zeroes` like so` perm = [0, 1, 2...7]` this is your match up configuration. \n\nIterate through zeroes vector with i = 0...zeroes.size(), match and find manhattan distance with `extras` index = `perm[i]`; add up the manhattan distance for current permutation of perm vector.\nShuffle through all possible permutaions. This way you match up cells with 0s to `extras`\'s cell in all potential ways.\n\nPick the permutation with minimum manhattan sum.\n\n# Complexity\n- Time complexity: O(n!) , n = number of cells with 0.\n While next_permutation() is O(n) for a single call, based on what I found out the [ammortized cost with large number of calls is O(1).](https://stackoverflow.com/questions/4973077/the-amortized-complexity-of-stdnext-permutation?rq=3) And since it is called n! times the overall complexity is O(n!).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) based on fixed size 3x3 grid.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int minMoves = INT_MAX;\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n\n vector<pair<int,int>> zeroes, extras;\n for (int i = 0; i < 3; ++i){\n for (int j = 0; j < 3; ++j){\n if (grid[i][j] == 0){\n zeroes.push_back(pair(i,j));\n continue;\n }\n else while(--grid[i][j]){\n extras.push_back(pair(i,j));\n }\n }\n }\n \n vector<int> perm(zeroes.size());\n iota(perm.begin(), perm.end(), 0);\n \n do{\n int moves = 0;\n for(int i = 0; i <zeroes.size(); ++i){\n moves+= manhattan(zeroes[i], extras[perm[i]]);\n }\n minMoves = min(minMoves, moves);\n }while(next_permutation(perm.begin(), perm.end()));\n\n return minMoves;\n }\n\n \n\n int manhattan(pair<int,int> p1, pair<int,int> p2){\n return abs(p1.first-p2.first) + abs(p1.second-p2.second);\n }\n};\n\n``` | 1 | 0 | ['Combinatorics', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | BEATS 93% !!! | beats-93-by-infinite_memory-dprq | Intuition\nUnderestimated the problem but was difficult to me than most mediums I guess.\nMy idea was to have 2 lists one with indexes of zeros and other with i | InFiNiTe_MeMoRy | NORMAL | 2024-01-13T19:30:55.500592+00:00 | 2024-01-13T19:30:55.500620+00:00 | 26 | false | # Intuition\nUnderestimated the problem but was difficult to me than most mediums I guess.\nMy idea was to have 2 lists one with indexes of zeros and other with indexes of 2s or 3s and then try each 2\'s or 3\'s for all zeros and taking minimum sum Manhattan distance.\n\n# Approach\nI created a class called Triad in which I stored indexes along with number of 1\'s. So in case of keeping track of zeros but even Triad was fine, neglecting the third parameter.\nNow for each zero in the list, I brute forced the optimal 1 it can take by making sure the Manhattan distance overall sum is minimum and while doing so, I simultaneuosly updated the count value so that after count reaches 1 no other 0 should be taking it. Then I updated the count value to original so that other cases can be tried out.\n\n# Code\n```\nclass Solution {\n\n class Triad\n {\n int x,y,count;\n\n Triad(int x,int y,int count)\n {\n this.x = x;\n this.y = y;\n this.count= count;\n }\n }\n\n public int solve(List<Triad> zeros,List<Triad> l,int ind)\n {\n if(ind == zeros.size())\n {\n return 0;\n }\n else\n {\n int k = Integer.MAX_VALUE;\n for(int i=0;i<l.size();i++)\n {\n Triad t = l.get(i);\n\n if(t.count>1)\n {\n t.count--;\n k = Math.min(k,Math.abs(t.x-zeros.get(ind).x)+Math.abs(t.y-zeros.get(ind).y)+solve(zeros,l,ind+1));\n t.count++;\n }\n }\n return k;\n }\n }\n\n\n public int minimumMoves(int[][] grid) {\n List<Triad> l = new ArrayList<>();\n List<Triad> zeros = new ArrayList<>();\n for(int i=0;i<grid.length;i++)\n {\n for(int j=0;j<grid[0].length;j++)\n {\n if(grid[i][j]>1)\n {\n l.add(new Triad(i,j,grid[i][j]));\n }\n if(grid[i][j] == 0)\n {\n zeros.add(new Triad(i,j,0));\n }\n }\n }\n\n return solve(zeros,l,0);\n }\n}\n\n//~ Varadraj \n``` | 1 | 0 | ['Array', 'Backtracking', 'Recursion', 'Java'] | 0 |
minimum-moves-to-spread-stones-over-grid | Detailed explanation with Approach + Comments | detailed-explanation-with-approach-comme-ev97 | Intuition\nEvery time we move a cell, we want to check the state of the grid, ie, if all cells have 1 stone each. Backtracking/Recursion can help us evaluate th | vishwajeet1 | NORMAL | 2024-01-08T17:17:54.126309+00:00 | 2024-01-08T17:17:54.126346+00:00 | 39 | false | # Intuition\nEvery time we move a cell, we want to check the state of the grid, ie, if all cells have 1 stone each. Backtracking/Recursion can help us evaluate that. This approach checks for all possible scenarios of filling up the grid while also checking the minimum number of moves required to do so in that iteration. \n\n# Approach\n1. Calculate `totalZeroes` in grid : if `totalZeroes = 0`, that means all cells have a stone, hence return `minimum moves required = 0`. \n2. Store `minimumMoves` for current state of grid in a `minMoves`. \n3. Iterate over grid elements. \n3. If `grid[i][j] = 0` then iterate over grid \'again\' to find the a cell : `grid[r][c]` which has stones > 1, this cell can move atleast 1 stone to `(i,j)`\n4. Calculate the absolute distance between the cells `grid[r][c]` and `grid[i][j]`\n(FYI : On a cartesian plane, this absolute distance between 2 points is known as Manhattan Distance). \n5. Add a stone to `grid[i][j]` and subtract a stone from `grid[r][c]`.\n6. The totalMoves required to move a stone from `(r,c)` to `(i,j)` is the the calculated `Manhattan Distance + Minimum Moves` required to move stones in the newly formed grid after moving from `(r,c)` to `(i,j)`. \n7. Update `minMoves` to have minimum of moves from current state to updated state. \n8. `Backtrack` to original state so subtract stone from `(i,j)` and add stone back to `(r,c)`.\n9. Return `minMoves`. \n\n# Complexity\n- Time complexity:\nO( n(Cell = 0) * n(Cell > 1) )\n\n- Space complexity:\nO( n(Cell =0 ) )\n\n# Code\n```\nclass Solution {\n public int minimumMoves(int[][] grid) {\n \n //after every move we want to evaluate the state of the grid\n //so that we can find what is the minimum number of moves yet calculated\n //that lead to a full house\n\n int totalZero = 0;\n\n for(int i = 0; i < 3; i++){\n for(int j = 0; j < 3; j++){\n if(grid[i][j]==0) totalZero++;\n }\n }\n\n if(totalZero == 0) return 0;\n\n int minMoves = Integer.MAX_VALUE;\n\n //go through grid\n for(int i = 0; i < 3; i++){\n for(int j = 0; j < 3; j++){\n //check if current element is 0\n if(grid[i][j] == 0){\n //check grid again to find nearest cell with stones > 1\n for(int r=0; r < 3; r++){\n for(int c = 0; c < 3; c++){\n if(grid[r][c] > 1){\n int distanceFromZero = Math.abs(r-i) + Math.abs(c-j);\n \n //at some point of computation, the extra stones from \'any\'(r,c) will end up at (i,j)\n //Add stone to [i][j]\n grid[i][j]++;\n //remove stone from [r][c]\n grid[r][c]--;\n\n //Total moves to move stone from (r,c) to (i,j) = \n //Distance between (r,c) and (i,j) + MinimumMoves in new state of grid\n //minimumMoves(grid) calculates moves left to do after moving 1 stone in the grid \n int totalMoves = distanceFromZero + minimumMoves(grid);\n \n //Is totalMoves the minimum totalMoves to fill the grid for this iteration?\n minMoves = Math.min(minMoves, totalMoves);\n \n //backtrack to original state after computing new state\n grid[r][c]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n\n return minMoves;\n }\n}\n``` | 1 | 0 | ['Backtracking', 'Recursion', 'Java'] | 0 |
minimum-moves-to-spread-stones-over-grid | Easy Recursive (Beats 100% of submissions) | easy-recursive-beats-100-of-submissions-t28de | Intuition\n Describe your first thoughts on how to solve this problem. \nUse Recursion for only few elements which are zero and more than 1\n# Approach\n Descri | robin1302 | NORMAL | 2023-12-15T15:47:09.276605+00:00 | 2023-12-15T15:50:00.327825+00:00 | 118 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Recursion for only few elements which are zero and more than 1\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create two list one containing Zero indexes and another for bulky indexes (> 1)\n- Recursively call for each Zero index and try to map it to different bulky elements in for loop.\n- Check if the grid value of element is still > 1.\n- Perform backtracking.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(M^N)$$ where N: Count of zero and M : Count of > 1\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\npublic class Solution {\n public int MinimumMoves(int[][] grid) {\n List<(int,int)> zero = new ();\n List<(int,int)> bulk = new();\n for(int i =0;i<3;i++)\n {\n for(int j =0;j<3;j++)\n {\n if (grid[i][j] == 0)\n {\n zero.Add((i,j));\n }\n if (grid[i][j] > 1)\n {\n bulk.Add((i,j));\n }\n }\n }\n int moves = 1000;\n Iterate(zero, bulk, 0, -1, -1, 0, grid,ref moves);\n return moves;\n }\n\n private void Iterate( List<(int,int)> zero, List<(int,int)> bulk, int index, int x, int y, int moves,int[][] grid, ref int minMoves)\n {\n if (index >= zero.Count)\n {\n minMoves = Math.Min(minMoves, moves);\n return;\n }\n (int a, int b) = zero[index];\n foreach((int k, int l) in bulk)\n {\n if (grid[k][l] > 1)\n {\n grid[k][l] -=1;\n grid[a][b] +=1;\n int val = Math.Abs(k-a) + Math.Abs(l-b);\n Iterate(zero, bulk, index+1, k, l, moves+val, grid,ref minMoves);\n grid[k][l] +=1;\n grid[a][b] -=1;\n } \n }\n }\n}\n``` | 1 | 0 | ['C#'] | 1 |
minimum-moves-to-spread-stones-over-grid | Backtracking with intuition explained. Faster than 95% | backtracking-with-intuition-explained-fa-lb81 | Intuition\nThe idea is to have all the zeros in a list and all the values > 1 in another list. Then bruteforce the solution using recursion.\n\n\n# Code\n\npubl | theaion | NORMAL | 2023-09-28T20:05:12.040009+00:00 | 2023-09-28T20:05:12.040032+00:00 | 109 | false | # Intuition\nThe idea is to have all the zeros in a list and all the values > 1 in another list. Then bruteforce the solution using recursion.\n\n\n# Code\n```\npublic class Solution {\n public int MinimumMoves(int[][] grid) {\n List<(int, int)> zeros = new();\n List<(int, int, int)> moreThanOne = new();\n\n for (int i = 0; i < grid.Length; i++)\n {\n for (int j = 0; j < grid[0].Length; j++)\n {\n if (grid[i][j] == 0)\n zeros.Add((i, j));\n else if (grid[i][j] > 1)\n moreThanOne.Add((i, j, grid[i][j] - 1));\n }\n }\n\n if (zeros.Count == 0)\n return 0;\n\n int min = int.MaxValue;\n CountMinimum(0, 0);\n\n return min;\n\n void CountMinimum(int i, int count)\n {\n if (i >= zeros.Count)\n {\n min = Math.Min(min, count);\n return;\n }\n\n for (int k = 0; k < moreThanOne.Count; k++)\n {\n var c = moreThanOne[k];\n if (c.Item3 == 0)\n continue;\n\n moreThanOne[k] = (moreThanOne[k].Item1, moreThanOne[k].Item2, moreThanOne[k].Item3 - 1);\n CountMinimum(i + 1, count + Math.Abs(c.Item1 - zeros[i].Item1) + Math.Abs(c.Item2 - zeros[i].Item2));\n moreThanOne[k] = (moreThanOne[k].Item1, moreThanOne[k].Item2, moreThanOne[k].Item3 + 1); //backtrack\n }\n }\n }\n}\n``` | 1 | 0 | ['Backtracking', 'Recursion', 'C#'] | 1 |
minimum-moves-to-spread-stones-over-grid | 0 ms || fastest || backtracking approach made easy. | 0-ms-fastest-backtracking-approach-made-zful9 | Intuition\nTo figure out backtracking , i wasn\'t able to get it in the first go , so i tried (GREEDY) filling zeros from the positions close to them having mor | dr_vegapunnk | NORMAL | 2023-09-18T12:29:00.865078+00:00 | 2023-09-18T12:29:00.865102+00:00 | 137 | false | # Intuition\nTo figure out backtracking , i wasn\'t able to get it in the first go , so i tried (GREEDY) filling zeros from the positions close to them having more stones and going on to filling the position with zero stones ,but was failing 91 test cases. \n\nthen it picked me that the ordering in which i am picking the zeros to fill, changes the answer. so this gave me the process of thinking in the direction of backtracking.\n \n# Approach\n\nmade a vectors of zeros(x,y) and excess stones namely stones(x,y,stones at (x,y)) \nthen i picked a zero position and tried all possible "stones" that can fill it.\n\nwe also dont want to go further when we are getting our temporary ans more than ans so we return at that point.\n\n\n\n# Code\n```\nclass Solution {\npublic:\n\n vector<vector<int>> stones,zeros;\n int n, m , ans = INT_MAX;\n\n void solve(int i, int& temp ){\n if(i == zeros.size()){\n ans = min(ans,temp);\n return;\n }\n if(temp>=ans) return;\n\n for(auto& it : stones){\n if(it[2]>1){\n temp += abs(zeros[i][0] - it[0]) + abs(zeros[i][1] - it[1]);\n it[2]--;\n solve(i+1,temp);\n it[2]++;\n temp -= abs(zeros[i][0] - it[0]) + abs(zeros[i][1] - it[1]);\n }\n }\n }\n\n int minimumMoves(vector<vector<int>>& grid) {\n\n n = grid.size();\n m = grid[0].size();\n for(int i = 0;i<n;i++){\n for(int j = 0;j<m;j++){\n if(grid[i][j] == 0){\n zeros.push_back({i,j});\n }\n else if(grid[i][j]>1) stones.push_back({i,j,grid[i][j]});\n }\n } \n int temp = 0;\n solve(0,temp);\n return ans;\n }\n};\n``` | 1 | 0 | ['Backtracking', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Go | Recursion+Backtracking | go-recursionbacktracking-by-b3k3r-dcrm | Intuition\n Describe your first thoughts on how to solve this problem. \nOnly factor in what it takes to move stones from a cell for the grid with > 1 stones to | b3k3r | NORMAL | 2023-09-15T02:25:05.342784+00:00 | 2023-09-15T02:25:05.342835+00:00 | 34 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly factor in what it takes to move stones from a cell for the grid with > 1 stones to one with 0 stones. Dont have to bother with any other cells. Distance can be calculated using equation for Manhattan distance from one cell to another.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a collection of cells with 0 stones and cells with more than 1 stone. For every empty cell iterate through possible cells to take from. Account for taking from that cell and recurse. Maintain a min for empty cell and return it.\n\nInitially I tried to simply iterate through all empty cells and calculate the min manhattan distance for each stone cell. The problem is in some instances, a stone would have to be taken from a cell that is not the min of that empty to allow for more other cells to take from their min, resulting in a smaller global min.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^m) (i think?) where n is the number of empty cells and m is the number of stone cells. While this is not good n and m will never exceed 4.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n+m) where n is the number of empty cells and m is the number of stone cells.\n\n# Code\n```\nvar emptyCells [][2]int\nvar stoneCells [][2]int\n\nfunc minimumMoves(grid [][]int) int {\n emptyCells = [][2]int{}\n stoneCells = [][2]int{}\n for i := 0; i < 3; i++ {\n for j := 0; j < 3; j++ {\n if grid[i][j] == 0 {\n emptyCells = append(emptyCells, [2]int{i, j})\n } else if grid[i][j] > 1 {\n stoneCells = append(stoneCells, [2]int{i, j})\n }\n }\n }\n return solve(grid, 0)\n}\n\nfunc solve(grid [][]int, emptyCellIdx int) int {\n if emptyCellIdx == len(emptyCells) { return 0 }\n curEmpty := emptyCells[emptyCellIdx]\n dist, ans := 0, math.MaxInt\n for i := 0; i < len(stoneCells); i++ {\n take := stoneCells[i]\n // Only take if the grid allows it\n if grid[take[0]][take[1]] == 1 { continue }\n // Calculate manhattan distance\n d := abs(curEmpty[0]-take[0]) + abs(curEmpty[1]-take[1])\n // Accout for taking this stone\n grid[take[0]][take[1]]--\n // Recurse\n dist = d + solve(grid, emptyCellIdx+1)\n // Backtrack\n grid[take[0]][take[1]]++\n ans = min(dist, ans)\n }\n return ans\n}\n\nfunc min(x, y int) int { if x < y { return x }; return y }\nfunc abs(x int) int { if x < 0 { return -x }; return x }\n``` | 1 | 0 | ['Backtracking', 'Recursion', 'Go'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++ || easy solution | c-easy-solution-by-shradhaydham24-09th | 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 | shradhaydham24 | NORMAL | 2023-09-11T14:39:26.518481+00:00 | 2023-09-11T14:39:26.518521+00:00 | 11 | 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 minimumMoves(vector<vector<int>>& grid) \n {\n int count=0;\n for(int i=0;i<3;i++)\n {\n for(int j=0;j<3;j++)\n {\n if(grid[i][j]==0)\n count++;\n }\n }\n if(count==0)\n return 0;\n int ans=INT_MAX;\n for(int i=0;i<3;i++)\n {\n for(int j=0;j<3;j++)\n {\n if(grid[i][j]==0)\n {\n for(int a=0;a<3;a++)\n {\n for(int b=0;b<3;b++)\n {\n int d=abs(a-i)+abs(b-j);\n if(grid[a][b]>1)\n {\n grid[a][b]--;\n grid[i][j]++;\n ans=min(ans,d+minimumMoves(grid));\n grid[a][b]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Python - short brute force | python-short-brute-force-by-ante-415k | Code\n\nclass Solution:\n def neigh(self, i):\n r, c = i//3, i%3\n for rr, cc in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]: \n if 0 < | Ante_ | NORMAL | 2023-09-10T11:15:02.298100+00:00 | 2023-09-10T11:15:02.298130+00:00 | 90 | false | # Code\n```\nclass Solution:\n def neigh(self, i):\n r, c = i//3, i%3\n for rr, cc in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]: \n if 0 <= rr < 3 and 0 <= cc < 3: yield rr*3+cc\n\n def minimumMoves(self, g):\n processing, end_state, seen, moves = [[g[i//3][i%3] for i in range(9)]], [1] * 9, set(), 0 \n while processing:\n next_processing = []\n for curr in processing:\n if curr == end_state: return moves\n seen.add(tuple(curr))\n for index in range(9):\n if curr[index] > 1:\n for nei in self.neigh(index):\n updated = curr[:]\n updated[nei] += 1\n updated[index] -= 1\n t = tuple(updated)\n if t not in seen: \n seen.add(t)\n next_processing.append(updated)\n processing = next_processing\n moves += 1\n\n \n``` | 1 | 0 | ['Hash Table', 'Backtracking', 'Queue', 'Python', 'Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | 100% fast ||Simple and Short Recurrsion || C++ | 100-fast-simple-and-short-recurrsion-c-b-k88h | 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 | ankush920 | NORMAL | 2023-09-10T07:29:16.512127+00:00 | 2023-09-10T07:29:16.512152+00:00 | 467 | 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:\nvector<pair<int ,int>>empty , stone;\nint minPossible( int ind, int n , vector<vector<int>>&grid ){\n if( ind == n) return 0; \n int x = empty[ind].first , y = empty[ind].second; \n int ans = INT_MAX;\n for(auto it : stone){\n int x1 = it.first , y1= it.second;\n if( grid[x1][y1] == 1 ) continue;\n int dis = abs( x1 -x) + abs( y1 - y); \n grid[x1][y1]--; \n ans = min( ans , dis + minPossible( ind+1, n, grid));\n grid[x1][y1]++; \n }\n\n return ans; \n}\n int minimumMoves(vector<vector<int>>& grid) {\n for( int i =0; i<3; i++){\n for( int j = 0; j<3; j++){\n if( grid[i][j] ==0) empty.push_back({i,j});\n if( grid[i][j] >1) stone.push_back({i,j});\n }\n } \n return minPossible(0, empty.size() , grid);\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | ✅ C++ ✅ | Easy | Backtracking | ✅Accepted✅ | c-easy-backtracking-accepted-by-mohit_ka-lmnf | \n\n# Intuition\nConstraints are very small, So apply brute force \n\n# Approach\n1. First check if any zero is present or not.\n2. Simply traverse the matrix.\ | mohit_kaushal | NORMAL | 2023-09-10T06:59:01.070877+00:00 | 2023-09-10T09:23:27.118875+00:00 | 192 | false | \n\n# Intuition\nConstraints are very small, So apply brute force \n\n# Approach\n1. First check if any zero is present or not.\n2. Simply traverse the matrix.\n3. If any cell is empty means equal to zero, again traverse the matrix to find non-zero cell having stones more than 1.\n4. For every target position of empty cell calculate number of moves.\n5. Temporarily move the stone to the target position by incrementing the value in the target cell and decrementing the value in the current cell.\n6. Backtrack to matrix to find the minimum moves for updated matrix.\n7. After backtracking restore matrix to original matrix.\n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<vector<int>>& grid ){\n int zero=0;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0)zero++;\n }\n }\n if(zero==0)return 0;\n int cnt=INT_MAX;\n\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0){\n for(int nRow=0;nRow<3;nRow++){\n for(int nCol=0;nCol<3;nCol++){\n if(grid[nRow][nCol]>1){\n int moves=abs(nRow-i)+abs(nCol-j);\n grid[nRow][nCol]--;\n grid[i][j]++;\n cnt=min(cnt,moves+solve(grid));\n grid[nRow][nCol]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n return cnt;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n return solve(grid);\n }\n};\n``` | 1 | 0 | ['Backtracking', 'Recursion', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | ✅ Easy || Backtracking || C++ || recursion|| Brute force | easy-backtracking-c-recursion-brute-forc-bvun | Intuition\nA cell with value zero can be be fill by any cell having value greater than 1\nTry all case and for minimum\n\n# Approach\nRecursion for all case \n\ | pradeep068 | NORMAL | 2023-09-10T06:29:39.545811+00:00 | 2023-09-10T06:29:39.545830+00:00 | 89 | false | # Intuition\nA cell with value zero can be be fill by any cell having value greater than 1\nTry all case and for minimum\n\n# Approach\nRecursion for all case \n\n# Code\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>> grid){\n vector<vector<int>>non;\n int x,y;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]>1) non.push_back({i,j});\n else if(grid[i][j]==0){\n x=i;\n y=j;\n }\n }\n }\n //base case : non of the cell have value greater than 1 \n if(non.size()==0) return 0; \n grid[x][y]=1;\n int mini=INT_MAX;\n for(auto it:non){\n grid[it[0]][it[1]]--;\n mini= min(mini, abs(it[0]-x) + abs(it[1]-y) + minimumMoves(grid));\n grid[it[0]][it[1]]++;\n }\n return mini;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | 🔥✅ Easy || Backtracking || C++ || 100% || Fully Commented🔥✅ | easy-backtracking-c-100-fully-commented-3jzfc | Intuition\n Describe your first thoughts on how to solve this problem. \nThe code is designed to find the minimum number of moves required to clear a grid where | Coder_Aayush | NORMAL | 2023-09-10T05:57:44.524110+00:00 | 2023-09-10T05:57:44.524138+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**The code is designed to find the minimum number of moves required to clear a grid where each cell contains a certain number of stones. The grid is represented as a 3x3 matrix, and the goal is to move stones from one cell to another in the most efficient way possible.**\n\nHere\'s the intuition for the code:\n\n- The steps function is a recursive function that explores all possible moves to clear the grid starting from a given cell (i, j).\n\n- The base case of the recursion is when i reaches 3, meaning we have reached the bottom row of the grid. In this case, no more moves are needed, so we return 0.\n\n- If the current cell (i, j) already contains stones (A[i][j] > 0), we move to the next cell in the same row (j+1) if possible, or the first cell of the next row (i+1, j=0) if we are at the end of the row. This is because we want to clear the current row before moving to the next.\n\n- If the current cell is empty (A[i][j] == 0), we consider all possible moves. For each move, we iterate through all other cells in the grid to find a target cell (a, b) with more than one stone (A[a][b] > 1). We then simulate the move by decrementing stones in the target cell and setting the current cell to 1.\n\n- We calculate the distance between the current cell (i, j) and the target cell (a, b) using abs(i - a) + abs(j - b) to measure how far the stones need to be moved.\n\n- We recursively call the steps function for the next cell, updating the minn variable with the minimum number of moves found so far.\n\n- After exploring all possible moves, we undo the move by incrementing stones in the target cell and setting the current cell back to 0 to backtrack and consider other possible moves.\n\n- Finally, we return the minimum number of moves (minn) found.\n\n- The minimumMoves function serves as the entry point and starts the recursive process from the top-left corner of the grid (cell (0, 0)). The goal is to find the minimum number of moves to clear the entire grid by moving stones strategically.\n\n# Code\n```\nclass Solution {\npublic:\n // Helper function to calculate the minimum number of moves\n int steps(int i, int j, vector<vector<int>>& A) {\n // Base case: If we have reached the end of the grid (i == 3), return 0 moves.\n if (i == 3) {\n return 0;\n }\n \n // If the current cell A[i][j] is already filled (A[i][j] > 0),\n // move to the next cell in the row or the next row.\n if (A[i][j] > 0) {\n if (j == 2) {\n return steps(i + 1, 0, A); // Move to the next row\n } else {\n return steps(i, j + 1, A); // Move to the next cell in the same row\n }\n }\n \n int minn = 1e9; // Initialize minn with a large value\n \n // Iterate through all possible moves in the grid\n for (int a = 0; a < 3; a++) {\n for (int b = 0; b < 3; b++) {\n \n // If the target cell A[a][b] has more than 1 stone, we can make a move\n if (A[a][b] > 1) {\n // Perform the move: decrement stones in A[a][b] and set A[i][j] to 1\n A[a][b] -= 1;\n A[i][j] = 1;\n \n // Calculate the distance between the current cell (i, j) and the target cell (a, b)\n int distance = abs(i - a) + abs(j - b);\n \n // Recursively call steps function for the next cell\n if (j == 2) {\n minn = min(minn, distance + steps(i + 1, 0, A)); // Move to the next row\n } else {\n minn = min(minn, distance + steps(i, j + 1, A)); // Move to the next cell in the same row\n }\n \n // Undo the move: increment stones in A[a][b] and set A[i][j] back to 0\n A[a][b] += 1;\n A[i][j] = 0;\n }\n }\n }\n \n return minn; // Return the minimum number of moves\n }\n \n // Main function to find the minimum moves to clear the grid\n int minimumMoves(vector<vector<int>>& A) {\n return steps(0, 0, A); // Start from the top-left corner of the grid\n }\n};\n\n``` | 1 | 0 | ['Backtracking', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Dijkstra | dijkstra-by-celonymire-qdev | Intuition\n Describe your first thoughts on how to solve this problem. \nI somehow couldn\'t come up with the right way to bruteforce, so I did an "optimized" b | CelonyMire | NORMAL | 2023-09-10T05:29:13.949454+00:00 | 2023-09-10T05:29:13.949481+00:00 | 30 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI somehow couldn\'t come up with the right way to bruteforce, so I did an "optimized" bruteforce via Dijkstra. Dijkstra can compute the minimum amount of operations to get to each possible state of the grid.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use a string to represent the state of the grid. For every state we go through, we figure out all the points that are `0` and have more than one stone. We can bruteforce trying to take a stone from all the cells with extra stone for every cell that needs a stone.\n\n# Code\n```\nclass Solution\n{\npublic:\n int minimumMoves(vector<vector<int>> &grid)\n {\n string state;\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n state.push_back(char(\'0\' + grid[i][j]));\n }\n }\n string final_state(9, \'1\');\n\n unordered_map<string, int> vis;\n priority_queue<pair<int, string>> q;\n vis[state] = 0;\n q.push({0, state});\n while (!q.empty())\n {\n auto [t, u] = q.top();\n t = -t;\n if (u == final_state)\n {\n return t;\n }\n q.pop();\n if (t > vis[u])\n continue;\n vector<pair<int, int>> need, extra;\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n char d = u[i * 3 + j];\n if (d > \'1\')\n {\n extra.push_back({i, j});\n }\n else if (d == \'0\')\n {\n need.push_back({i, j});\n }\n }\n }\n for (auto [i1, j1] : need)\n {\n for (auto [i2, j2] : extra)\n {\n u[i1 * 3 + j1]++;\n u[i2 * 3 + j2]--;\n int new_t = t + abs(i1 - i2) + abs(j1 - j2);\n if (!vis.count(u) || new_t < vis[u])\n {\n vis[u] = new_t;\n q.push({-new_t, u});\n }\n u[i1 * 3 + j1]--;\n u[i2 * 3 + j2]++;\n }\n }\n }\n return -1;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Heap (Priority Queue)', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Best C++ sol | best-c-sol-by-raveeshgoyal-frpw | Code\n\nclass Solution {\npublic:\n void helper(int i,int j,int curr,int &ans,vector<vector<int>>& grid){\n if(i==3){\n ans=min(ans,curr); | raveeshgoyal | NORMAL | 2023-09-10T04:57:14.588263+00:00 | 2023-09-10T04:57:28.359160+00:00 | 177 | false | # Code\n```\nclass Solution {\npublic:\n void helper(int i,int j,int curr,int &ans,vector<vector<int>>& grid){\n if(i==3){\n ans=min(ans,curr); \n return;\n }\n if(j==3){\n helper(i+1,0,curr,ans,grid);\n return;\n }\n if(grid[i][j]!=0){\n helper(i,j+1,curr,ans,grid);\n return;\n }\n \n for(int m=0;m<3;m++){\n for(int n=0;n<3;n++){\n if(grid[m][n]>1){\n grid[m][n]--;\n grid[i][j]++;\n int val=abs(m-i) + abs(n-j);\n helper(i,j,curr+val,ans,grid);\n grid[m][n]++;\n grid[i][j]--;\n }\n }\n }\n \n }\n int minimumMoves(vector<vector<int>>& grid) {\n int ans=INT_MAX;\n helper(0,0,0,ans,grid);\n return ans;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | EASY SOLUTION || C++ || EXPLANATION | easy-solution-c-explanation-by-amol_2004-n6eg | Intuition\n Describe your first thoughts on how to solve this problem. \nSince the constraints are very less we can apply recursion here.\n\n\n# Approach\n Desc | amol_2004 | NORMAL | 2023-09-10T04:41:58.020813+00:00 | 2023-09-10T04:41:58.020832+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n***Since the constraints are very less we can apply recursion here.***\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n`For every cell find all the possible cells that can give 1 stone and then take its minimum`\n\n\n# Code\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n int zero = 0;\n for(int i = 0; i < 3; i++)\n for(int j = 0; j < 3; j++)\n if(grid[i][j] == 0)\n zero++;\n if(zero == 0)\n return 0;\n\n int ans = INT_MAX;\n\n for(int i = 0; i < 3; i++){\n for(int j = 0; j < 3; j++){\n if(grid[i][j] == 0){\n for(int r = 0; r < 3; r++){\n for(int c = 0; c < 3; c++){\n int dis = abs(r - i) + abs(c - j);\n if(grid[r][c] > 1){\n grid[r][c]--;\n grid[i][j]++;\n ans = min(ans, dis + minimumMoves(grid));\n grid[r][c]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n};\n```\n\n | 1 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | ✅Recursion✅ || Beats 100% 🏆 || Brute Force || c++ | recursion-beats-100-brute-force-c-by-nit-sndc | \n\n\n# Code\n\nclass Solution {\npublic:\n int solve(vector<vector<int>>& vpG, vector<vector<int>>& vpS, int i) {\n if (i == vpS.size()) return 0;\n\ | trinosauraus629 | NORMAL | 2023-09-10T04:34:58.234327+00:00 | 2023-09-10T05:19:02.935325+00:00 | 18 | false | \n\n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<vector<int>>& vpG, vector<vector<int>>& vpS, int i) {\n if (i == vpS.size()) return 0;\n\n int ans = INT_MAX;\n // Take from this\n for (auto& x : vpG) {\n int curr = 0;\n if (x[0] > 0) {\n curr += abs(vpS[i][0] - x[1]) + abs(vpS[i][1] - x[2]);\n x[0]--;\n curr += solve(vpG, vpS, i + 1);\n x[0]++;\n ans = min(ans, curr);\n }\n }\n return ans;\n }\n\n int minimumMoves(vector<vector<int>>& grid) {\n vector<vector<int>> vpG, vpS;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (grid[i][j] > 1) {\n vpG.push_back({ grid[i][j] - 1, i, j }); // Decrease even numbers by 1\n \n }\n if (grid[i][j] == 0) {\n vpS.push_back({ i, j });\n }\n }\n }\n\n int ans = 0;\n return solve(vpG, vpS, 0);\n }\n};\n\n``` | 1 | 0 | ['Backtracking', 'Greedy', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Code giving TLE on one test case | code-giving-tle-on-one-test-case-by-saks-6whr | \nclass Solution {\npublic:\n \n bool isValid(int x,int y)\n {\n if(x<0 || y<0 || x>=3 || y>=3)\n return false;\n \n re | saksham_singhal_2001 | NORMAL | 2023-09-10T04:28:37.572019+00:00 | 2023-09-10T04:44:17.290175+00:00 | 236 | false | ```\nclass Solution {\npublic:\n \n bool isValid(int x,int y)\n {\n if(x<0 || y<0 || x>=3 || y>=3)\n return false;\n \n return true;\n }\n \n vector<int> mnMoves(vector<vector<int>> &grid,int x,int y)\n {\n // cout<<x<<" "<<y<<" ";\n queue<vector<int>> q;\n q.push({x,y});\n \n vector<vector<bool>> vis(3,vector<bool>(3));\n vis[x][y] = true;\n int step = 0;\n bool found = false;\n \n int r[] = {-1,1,0,0};\n int c[] = {0,0,1,-1};\n vector<int> ans;\n \n while(!q.empty())\n {\n int sz = q.size();\n \n while(sz--)\n {\n vector<int> v = q.front();\n q.pop();\n \n if(grid[v[0]][v[1]]>1)\n {\n // grid[v[0]][v[1]]--;\n // grid[x][y]++;\n ans = {v[0],v[1]};\n found = true;\n break;\n }\n \n for(int i=0;i<4;i++)\n {\n int nx = v[0]+r[i];\n int ny = v[1]+c[i];\n \n if(isValid(nx,ny) && !vis[nx][ny])\n {\n vis[nx][ny] = true;\n q.push({nx,ny});\n }\n }\n }\n \n if(found)\n break;\n \n step++;\n }\n // cout<<step<<endl;\n ans.push_back(step);\n return ans;\n }\n \n int comb(vector<vector<int>> &zeros,vector<bool> &vis,vector<vector<int>> &grid)\n {\n int ans = 1e3;\n \n for(int i=0;i<zeros.size();i++)\n {\n if(!vis[i])\n {\n vis[i] = true;\n \n vector<int> v = mnMoves(grid,zeros[i][0],zeros[i][1]);\n \n int temp = v[2];\n grid[v[0]][v[1]]--;\n grid[zeros[i][0]][zeros[i][1]]++;\n \n ans = min(ans,temp+comb(zeros,vis,grid));\n \n vis[i] = false;\n grid[v[0]][v[1]]++;\n grid[zeros[i][0]][zeros[i][1]]--;\n }\n }\n \n return (ans==1e3?0:ans);\n }\n \n int minimumMoves(vector<vector<int>>& grid) {\n \n int ans = 0;\n vector<vector<int>> zeros;\n \n for(int i=0;i<3;i++)\n {\n for(int j=0;j<3;j++)\n {\n if(grid[i][j]==0)\n {\n // ans += mnMoves(grid,i,j);\n zeros.push_back({i,j});\n }\n }\n }\n \n if(zeros.size()==0)\n return 0;\n \n vector<bool> vis(zeros.size());\n \n return comb(zeros,vis,grid);\n \n }\n};\n```\n\nWhat all I have done here is , there will be certian number of \'zero-squares\'. I tried every combination possible to fill those square. For example if there are three squares with 0, i have tried to fill every combination and saw which gives minimum answer like (first,second,third), then (first,third,second), then (second,first,third) and so on....\n\n\nThe code is giving TLE on case {{9,0,0},(0,0,0},{0,0,0}}. However, the same test when I give as custom test passes. I don\'t understand the mistake here. From my point of view, its time complexity will be O(9!). Can anyone please help\n\nThanx in advance | 1 | 0 | ['Breadth-First Search', 'Recursion', 'C'] | 1 |
minimum-moves-to-spread-stones-over-grid | Bitmasking | bitmasking-by-khem_404-92ml | 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 | khem_404 | NORMAL | 2023-09-10T04:25:14.379149+00:00 | 2023-09-10T04:25:14.379165+00:00 | 37 | 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 find( vector<vector<int>>&dp,vector<vector<int>>&v,vector<vector<int>>&p,int i,int mask)\n {\n int sz = v.size();\n if(i>=sz)\n return 0; \n if(dp[i][mask]!=-1)\n return dp[i][mask];\n int ans =INT_MAX;\n for(int k=0;k<p.size();k++)\n {\n if((1<<k)&mask)\n continue;\n int sum =abs(v[i][0]-p[k][0])+abs(v[i][1]-p[k][1]);\n ans = min(ans,sum+find(dp,v,p,i+1,mask|(1<<k)));\n }\n return dp[i][mask]=ans;\n }\n int minimumMoves(vector<vector<int>>& g) {\n vector<vector<int>>v,p;\n for(int i=0;i<g.size();i++)\n {\n for(int j=0;j<g[0].size();j++)\n {\n while(g[i][j]>1)\n {\n v.push_back({i,j});\n g[i][j]--;\n }\n if(g[i][j]==0)\n p.push_back({i,j});\n }\n }\n \n vector<vector<int>>dp(10,vector<int>(1<<10,-1));\n return find(dp,v,p,0,0);\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | [Dart] Simple BFS Solution | dart-simple-bfs-solution-by-hyungzin-56jn | Intuition\ndart simple BFS solution\n\n# Approach\nvisit for back track\nfocus on the stones > 1\nadd the list (deep copy with original) at every new case\n\n# | hyungzin | NORMAL | 2023-09-10T04:09:33.170434+00:00 | 2023-09-10T04:09:33.170454+00:00 | 162 | false | # Intuition\ndart simple BFS solution\n\n# Approach\nvisit for back track\nfocus on the stones > 1\nadd the list (deep copy with original) at every new case\n\n# Complexity\n- Time complexity:\n\n\n- Space complexity:\n\n# Code\n```\nimport \'dart:collection\';\nclass Solution {\n final visit = <String>{};\n int minimumMoves(List<List<int>> grid) {\n int cnt = 0;\n final q = Queue<List<List<int>>>();\n q.add(grid);\n visit.add(grid.expand((row) => row).join());\n while (q.isNotEmpty){\n final newQ = Queue<List<List<int>>>();\n while (q.isNotEmpty){\n final g = q.removeFirst();\n \n int y0 = -1;\n int x0 = -1;\n loop: for (int i = 0; i < 3; i++){\n for (int j = 0; j < 3; j++){\n if (g[i][j] > 1){\n y0 = i;\n x0 = j;\n break loop;\n }\n }\n }\n // print(\'g: $g, cnt: $cnt, y: $y0, x: $x0\');\n if (y0 == -1) return cnt;\n // up\n if (y0 > 0){\n final newG = g.map((list) => List<int>.from(list)).toList();;\n newG[y0 - 1][x0]++;\n newG[y0][x0]--;\n final sG = newG.expand((row) => row).join();\n if (!visit.contains(sG)){\n visit.add(sG);\n newQ.add(newG);\n }\n }\n // down\n if (y0 < 2){\n final newG = g.map((list) => List<int>.from(list)).toList();;\n newG[y0 + 1][x0]++;\n newG[y0][x0]--;\n final sG = newG.expand((row) => row).join();\n if (!visit.contains(sG)){\n visit.add(sG);\n newQ.add(newG);\n }\n }\n// left\n if (x0 > 0){\n final newG = g.map((list) => List<int>.from(list)).toList();;\n newG[y0][x0 - 1]++;\n newG[y0][x0]--;\n final sG = newG.expand((row) => row).join();\n if (!visit.contains(sG)){\n visit.add(sG);\n newQ.add(newG);\n }\n }\n// right\n if (x0 < 2){\n final newG = g.map((list) => List<int>.from(list)).toList();;\n newG[y0][x0 + 1]++;\n newG[y0][x0]--;\n final sG = newG.expand((row) => row).join();\n if (!visit.contains(sG)){\n visit.add(sG);\n newQ.add(newG);\n }\n }\n }\n q.addAll(newQ);\n cnt++;\n }\n return cnt;\n }\n}\n``` | 1 | 0 | ['Breadth-First Search', 'Dart'] | 0 |
minimum-moves-to-spread-stones-over-grid | Easy c++ Recursion ✅✅✅✅ | easy-c-recursion-by-rohan_cs-n9z7 | 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 | rohan_cs | NORMAL | 2023-09-10T04:08:03.652041+00:00 | 2023-09-10T04:08:03.652063+00:00 | 180 | 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 helper(vector<vector<int>>& grid){\n int cnt=0;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++) if(grid[i][j]==1) cnt++;\n }\n // cout<<cnt;\n if(cnt==9) return 0;\n int res =1e9;\n \n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n for(int m=0;m<3;m++){\n for(int n=0;n<3;n++){\n if(grid[i][j]==0&&grid[m][n]>1){\n grid[i][j]++;\n grid[m][n]--;\n res = min(res,abs(i-m)+abs(j-n)+helper(grid));\n grid[i][j]--;\n grid[m][n]++;\n }\n }\n }\n }\n }\n return res;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n return helper(grid);\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Java || Easy Solution || recusrion | java-easy-solution-recusrion-by-akash280-s69e | \nclass Solution {\n public int minimumMoves(int[][] grid) {\n int count=0;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n | akash2802 | NORMAL | 2023-09-10T04:07:05.066820+00:00 | 2023-09-10T04:07:05.066844+00:00 | 222 | false | ```\nclass Solution {\n public int minimumMoves(int[][] grid) {\n int count=0;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0)\n count++;\n }\n }\n return findMoves(grid,0,count);\n }\n public int findMoves(int grid[][],int curr,int count){\n if(count==0){\n return curr;\n }\n \n int min=Integer.MAX_VALUE;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0){ \n for(int k=0;k<3;k++){\n for(int l=0;l<3;l++){\n if(grid[k][l]>1){\n int t=Math.abs(i-k)+Math.abs(j-l);\n grid[i][j]=1;\n grid[k][l]--;\n min=Math.min(findMoves(grid,curr+t,count-1),min);\n grid[i][j]=0;\n grid[k][l]++;\n }\n }\n }\n }\n \n }\n }\n return min;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
minimum-moves-to-spread-stones-over-grid | Python brute force | python-brute-force-by-zonda_yang-x9bu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Code\n\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\ | zonda_yang | NORMAL | 2023-09-10T04:05:12.385161+00:00 | 2023-09-10T04:05:12.385181+00:00 | 1,025 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n zero_list = []\n more_list = []\n for y in range(3):\n for x in range(3):\n if grid[y][x] == 0:\n zero_list.append((y, x))\n elif grid[y][x] > 1:\n for _ in range(grid[y][x] - 1):\n more_list.append((y, x))\n def get_res(m_list, z_list):\n ans = 0\n for (more_y, more_x) in m_list:\n curr = float("inf")\n curr_index = -1\n curr_y, curr_x = -1, -1\n for i, (z_y, z_x) in enumerate(z_list):\n temp = abs(z_y - more_y) + abs(z_x - more_x)\n if temp < curr:\n curr = temp\n curr_index = i\n curr_y, curr_x = z_y, z_x\n z_list.pop(curr_index)\n ans += curr\n return ans\n \n result = float("inf")\n for temp in itertools.permutations(more_list):\n result = min(result, get_res(temp, zero_list[:]))\n return result\n``` | 1 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Easyy to understand | easyy-to-understand-by-priyanshu1880-x6s8 | 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 | priyanshu1880 | NORMAL | 2023-09-10T04:02:52.668201+00:00 | 2023-09-10T04:02:52.668227+00:00 | 67 | 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 ans = 1e9;\n void solve(vector<vector<int>> &grid , int idx , int cnt , int n , int m)\n {\n if(idx >= 9)\n {\n int flag = 1;\n for(int i = 0;i<3;i++)\n {\n for(int j = 0;j<3;j++) \n {\n if(grid[i][j] != 1) flag = false;\n }\n }\n if(flag) ans = min(ans , cnt); \n return;\n }\n \n\n int x = idx/3 , y = idx%3;\n if(grid[x][y] == 0)\n {\n for(int i = 0;i<3;i++)\n {\n for(int j = 0;j<3;j++) \n {\n if(grid[i][j] > 1)\n {\n grid[i][j]-=1;\n grid[x][y]+=1;\n solve(grid , idx+1 , cnt + abs(x-i) + abs(y-j) , n , m);\n grid[x][y]-=1;\n grid[i][j]+=1;\n }\n }\n }\n }\n else solve(grid , idx+1 , cnt , n , m);\n }\n int minimumMoves(vector<vector<int>>& grid) \n {\n int n = grid.size(); \n int m = grid.size();\n solve(grid , 0 , 0 , n , m);\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | BFS on all possible states | bfs-on-all-possible-states-by-theabbie-qi5q | \nfrom collections import deque\n\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n def key(g):\n res = 0\n | theabbie | NORMAL | 2023-09-10T04:02:28.002796+00:00 | 2023-09-10T04:02:28.002818+00:00 | 279 | false | ```\nfrom collections import deque\n\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n def key(g):\n res = 0\n for i in range(3):\n for j in range(3):\n res = 10 * res + g[i][j]\n return res\n target = [[1] * 3 for _ in range(3)]\n q = deque([(grid, 0)])\n v = {key(grid)}\n while len(q) > 0:\n curr, steps = q.pop()\n if curr == target:\n return steps\n for i in range(3):\n for j in range(3):\n if curr[i][j] > 1:\n for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n k = i + dx\n l = j + dy\n if 0 <= k < 3 and 0 <= l < 3:\n newcurr = [[curr[i][j] for j in range(3)] for i in range(3)]\n newcurr[i][j] -= 1\n newcurr[k][l] += 1\n newkey = key(newcurr)\n if newkey not in v:\n v.add(newkey)\n q.appendleft((newcurr, steps + 1))\n return -1\n``` | 1 | 0 | [] | 0 |
minimum-moves-to-spread-stones-over-grid | Precompute all from target | precompute-all-from-target-by-theabbie-0x35 | null | theabbie | NORMAL | 2025-04-10T07:21:38.779092+00:00 | 2025-04-10T07:21:38.779092+00:00 | 1 | false | ```python3 []
from collections import deque
dp = {}
initial = (1,) * 9
queue = deque([initial])
dp[initial] = 0
neighbors = [[] for _ in range(9)]
for i in range(9):
r, c = i // 3, i % 3
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < 3 and 0 <= nc < 3:
neighbors[i].append(nr * 3 + nc)
while queue:
state = queue.popleft()
d = dp[state]
for i in range(9):
if state[i]:
for j in neighbors[i]:
ns = list(state)
ns[i] -= 1
ns[j] += 1
ns = tuple(ns)
if ns not in dp:
dp[ns] = d + 1
queue.append(ns)
class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
state = tuple(grid[i][j] for i in range(3) for j in range(3))
return dp[state]
``` | 0 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++ Easy Backtracking Algorithm with comments | c-easy-backtracking-algorithm-with-comme-gx0r | Code | ronakj527 | NORMAL | 2025-03-22T21:29:04.179704+00:00 | 2025-03-22T21:29:04.179704+00:00 | 6 | false |
# Code
```cpp []
class Solution {
public:
int helper(vector<pair<int, int>> &toFill, vector<vector<int>>& av, int i) {
/* i == toFill.size() means we have iterated over all toFill elements. All elements have been filled, return 0 */
if (i == toFill.size()) return 0;
int answer = INT_MAX;
/* Iterate over each available slot and recursively try to fill the next toFill index */
for (int j = 0; j < av.size(); j++) {
/* av[j][2] == 0 means count == 0, meaning this available index does not have any extra stone to share */
if (av[j][2] == 0) continue;
/* consider using stone from this available index. Its count will decrement by one. */
av[j][2]--;
/* distance from this available slot is |x1-x2| + |y1-y2| ;
Example: consider toFill slot is 0,0 and available slot is 2, 1.. The distance between them will be |0-2| + |0-1| = 3; */
int distFromAv = abs(av[j][0] - toFill[i].first) + abs(av[j][1] - toFill[i].second);
/* Total distance if we pick this available slot = distance for this slot + minimum distance for the other toFill slots */
int dist = helper(toFill, av, i+1) + disFromAv;
/* if picking this slot gave the minimum distance, store it in answer. We will return it to the caller after evaluating all available slots. */
if (dist < answer) {
answer = dist;
}
/* increment the number of available stones for this slot, and check the value for other available slots through this for loop. */
av[j][2]++;
}
return answer;
}
int minimumMoves(vector<vector<int>>& grid) {
/* vector available contains list of available spaces along with number of stones available : {rowNum, colNum, count} */
vector<vector<int>> available;
/* toFill contains indexes that currently have 0 stones and which need to be filled : {rowNum, colNum} */
vector<pair<int, int>> toFill;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid.size(); j++) {
/* Iterate over each entry of grid and fill available and toFill vectors */
if (grid[i][j] == 0) {
/* This index has 0 stones. Add it to toFill vector */
toFill.push_back({i, j});
} else if (grid[i][j] > 1) {
/* This index has more than 1 stones. Store its index, and extra stones in available vector */
std::vector<int> vec = {i, j, grid[i][j] -1};
available.push_back(vec);
}
}
}
/* call helper which will recursively iterate over all elements in toFill and consider each case from avaialble vector */
return helper(toFill, available, 0 /* toFill index */);
}
};
``` | 0 | 0 | ['Backtracking', 'Greedy', 'Recursion', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Recursion | TC: 2ms | Java | recursion-tc-2ms-java-by-mp78xiambv-dveo | Intuition
For every cell with zero, we have options to take it from cells with > 1
ApproachComplexity
Time complexity: 9 * (number of cells with > 1) ^(number o | mP78XiaMbv | NORMAL | 2025-02-18T08:55:00.023493+00:00 | 2025-02-18T08:55:00.023493+00:00 | 7 | false | # Intuition
- For every cell with zero, we have options to take it from cells with > 1
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: 9 * (number of cells with > 1) ^(number of cells == 0)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: number of cells with 0
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
int ans = Integer.MAX_VALUE;
public int minimumMoves(int[][] grid) {
dfs(grid, 0);
return ans;
}
void dfs(int[][] grid, int moves) {
int r = -1, c = -1;
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
if(grid[i][j] == 0) {
r = i;
c = j;
break;
}
}
}
if(r == -1) {
ans = Math.min(moves, ans);
return;
}
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
if(grid[i][j] > 1) {
grid[i][j]--;
grid[r][c] = 1;
moves += Math.abs(r - i) + Math.abs(c - j);
dfs(grid, moves);
grid[i][j]++;
moves -= Math.abs(r - i) + Math.abs(c - j);
grid[r][c] = 0;
}
}
}
}
}
``` | 0 | 0 | ['Java'] | 0 |
minimum-moves-to-spread-stones-over-grid | python backtrack | python-backtrack-by-tianwen0815-1ujc | IntuitionThe problem is akin to finding an optimal assignment of items (stones) to positions. A brute-force approach can be used, employing backtracking to try | tianwen0815 | NORMAL | 2025-01-06T00:20:08.733922+00:00 | 2025-01-06T00:20:08.733922+00:00 | 11 | false | ### Intuition
The problem is akin to finding an optimal assignment of items (stones) to positions. A brute-force approach can be used, employing backtracking to try all possible assignments of stones to empty grid spots and then calculating the minimum distance for each assignment.
### Approach
- **Representation of grid state**: Stones that need to be moved and positions that are targets (empty) are extracted from the grid.
- **Backtracking mechanism**: A backtracking function generates all possible ways to assign stones to empty spots.
- **Distance calculation**: For each assignment, the total movement cost is calculated by summing up the Manhattan distances from each stone's original position to its assigned new position.
- **Optimization**: The minimum of these calculated distances across all assignments is kept to determine the least number of moves required.
### Complexity
- **Time complexity**: The time complexity here is exponential, specifically $O(m!)$, where $m$ is the number of stones that need to be moved. This complexity arises from generating all permutations of assignments of stones to target positions.
- **Space complexity**: The space complexity is $O(m)$, due to the storage required for the recursion stack and for storing the current assignment in `backtrack`.
### Code
```python3 []
# backtracking, just like secret santa
class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
more_stones = [[(i, j)] * (grid[i][j] - 1) for i in range(3) for j in range(3) if grid[i][j] > 1]
more_stones = [col for row in more_stones for col in row]
no_stones = [(i, j) for i in range(3) for j in range(3) if grid[i][j] == 0]
res = float("inf")
m = len(more_stones)
assignment = [None] * m
all_assignments = []
def backtrack(i):
if i == m:
all_assignments.append(assignment.copy())
for j in range(m):
if j not in assignment:
assignment[i] = j
backtrack(i + 1)
assignment[i] = None
def calcualte_distance(x, y):
return abs(x[0] - y[0]) + abs(x[1] - y[1])
def calculate_moves(assignment):
total = 0
for i, j in enumerate(assignment):
total += calcualte_distance(more_stones[i], no_stones[j])
return total
backtrack(0)
for assign in all_assignments:
res = min(res, calculate_moves(assign))
return res
``` | 0 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Same As Sliding Puzzle using BFS and Backtrack | same-as-sliding-puzzle-using-bfs-and-bac-4qew | IntuitionApproachComplexity
Time complexity:
Space complexity:
Same Pattern Problemhttps://leetcode.com/problems/sliding-puzzle/description/Code | shido_AKV | NORMAL | 2025-01-02T19:05:35.887335+00:00 | 2025-01-02T19:05:35.887335+00:00 | 22 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Same Pattern Problem
https://leetcode.com/problems/sliding-puzzle/description/
# Code
```cpp []
class Solution {
public:
// (2/1/2025)
// shree shivay namstubhaym
int n, m;
int minimumMoves(vector<vector<int>>& grid) {
// We need to check if after performing moves, the grid becomes the target grid
string desc(9, '1');
n = grid.size();
m = grid[0].size();
string src = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
src += to_string(grid[i][j]);
}
}
map<pair<int, int>, int> m1;
map<int, pair<int, int>> m2;
int l = 0, r = 0;
for (int i = 0; i < 9; i++) {
if (i == 3 || i == 6) {
l++;
r = 0;
}
m1[{l, r}] = i;
m2[i] = {l, r++};
}
unordered_map<string, int> vis;
queue<pair<int, string>> q;
q.push({0, src});
vis[src] = 1;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
while (!q.empty()) {
int c = q.front().first;
string str = q.front().second;
q.pop();
if (str == desc) return c;
for (int i = 0; i < str.size(); i++) {
if (stoi(string(1, str[i])) > 1) {
int x = m2[i].first;
int y = m2[i].second;
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {
int index = m1[{nx, ny}];
int num1 = stoi(string(1, str[i])) - 1;
int num2 = stoi(string(1, str[index])) + 1;
str[i] = to_string(num1)[0];
str[index] = to_string(num2)[0];
if (!vis[str]) {
vis[str] = 1;
q.push({c + 1, str});
}
str[i] = to_string(num1 + 1)[0];
str[index] = to_string(num2 - 1)[0];
}
}
}
}
}
return -1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++ | c-by-tinachien-9lip | \nclass Solution {\n int ret = INT_MAX;\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n dfs(0, 0, grid);\n return ret;\n }\n | TinaChien | NORMAL | 2024-12-15T16:23:52.773791+00:00 | 2024-12-15T16:23:52.773816+00:00 | 6 | false | ```\nclass Solution {\n int ret = INT_MAX;\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n dfs(0, 0, grid);\n return ret;\n }\n \n void dfs(int cur, int moves, vector<vector<int>>& grid){\n if( moves >= ret )\n return;\n if(cur == 9){\n ret = min(ret, moves);\n return;\n }\n int i = cur / 3;\n int j = cur % 3;\n if(grid[i][j] > 0)\n return dfs(cur+1, moves, grid);\n for(int x = 0; x < 3; x++){\n for(int y = 0; y < 3; y++){\n if(grid[x][y] > 1){\n grid[x][y] -= 1;\n grid[i][j] += 1;\n dfs(cur+1, moves+abs(x-i) + abs(y-j), grid);\n grid[x][y] += 1;\n grid[i][j] -= 1; \n }\n }\n }\n }\n};\n``` | 0 | 0 | [] | 0 |
minimum-moves-to-spread-stones-over-grid | BFS | bfs-by-linda2024-jsyp | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | linda2024 | NORMAL | 2024-12-20T20:29:44.162220+00:00 | 2024-12-20T20:29:44.162220+00:00 | 10 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
private void BFS(List<int[]> empties, Dictionary<(int, int), int> dict, int idx, int moves, ref int minMoves)
{
int len = empties.Count;
if(idx >= len)
{
minMoves = Math.Min(minMoves, moves);
return;
}
int x = empties[idx][0], y = empties[idx][1];
foreach(var kvp in dict)
{
var key = kvp.Key;
int val = kvp.Value;
if(val > 0)
{
dict[key]--;
int nextVal = Math.Abs(key.Item1-x) + Math.Abs(key.Item2-y);
BFS(empties, dict, idx+1, moves+nextVal, ref minMoves);
dict[key]++;
}
}
}
public int MinimumMoves(int[][] grid) {
// pre build co-or of stones which can be moved, que of empty co-ors
Dictionary<(int, int), int> dict = new();
List<int[]> empties = new();
int rows = grid.Length, cols = grid[0].Length, res = 0;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
int val = grid[i][j];
if( val == 1)
continue;
if(val == 0)
empties.Add([i, j]);
else
dict.Add((i, j), val-1);
}
}
int minMoves = 9*9;
BFS(empties, dict, 0, 0, ref minMoves);
return minMoves;
}
}
``` | 0 | 0 | ['C#'] | 0 |
minimum-moves-to-spread-stones-over-grid | Bruteforced DFS recursion. Beats 100% | bruteforced-dfs-recursion-beats-100-by-n-7ha3 | Intuition\nI can\'t think of a way to solve this without bruteforce.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo omit redund | novodimaporo | NORMAL | 2024-11-12T08:32:01.499372+00:00 | 2024-11-12T08:44:23.553919+00:00 | 14 | false | # Intuition\nI can\'t think of a way to solve this without bruteforce.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo omit redundant computations, filter-out the cells that we are interested. The empty cells, and the cells with more than 1 stones. Bruteforced with DFS recursion.\n<!-- Describe your approach to solving the problem. -->\n\n# Improvements\nPossible improvement is to apply pruning. Please suggest how.\n\n# Code\n```kotlin []\nclass Solution {\n\n data class Cell(val x: Int, val y: Int, val stoneCount: Int = 0)\n\n // Terminal case is if there is no more empty cells.\n // Bruteforced. Take the mininum number of moves\n // by trying all possible sorce of stone to fill\n // an empty cell.\n fun moveStone(\n moves: Int, \n emptyCells: List<Cell>, \n twoUpCells: List<Cell>\n ): Int {\n if (emptyCells.isEmpty()) return moves\n\n val emptyCell = emptyCells.first()\n var minChildMove = Int.MAX_VALUE\n\n twoUpCells.forEachIndexed {\n i, twoUpCell ->\n\n val newTwoUpCells = twoUpCells.toMutableList()\n val cellStoneMove = abs(emptyCell.x - twoUpCell.x) +\n abs(emptyCell.y - twoUpCell.y)\n\n if (twoUpCell.stoneCount > 2) {\n newTwoUpCells[i] = twoUpCell.copy(stoneCount = twoUpCell.stoneCount-1)\n } else {\n newTwoUpCells.removeAt(i)\n }\n\n val childMove = moveStone(\n moves + cellStoneMove,\n emptyCells.drop(1),\n newTwoUpCells\n )\n\n if (childMove < minChildMove) { \n minChildMove = childMove \n }\n }\n\n return minChildMove\n }\n\n fun minimumMoves(grid: Array<IntArray>): Int {\n // Preprocess the grid, collect empty cells and \n // cells with 2 or more stones.\n var emptyCells = mutableListOf<Cell>()\n var twoUpCells = mutableListOf<Cell>()\n\n grid.forEachIndexed {\n rowIndex, row ->\n row.forEachIndexed {\n columnIndex, stoneCount ->\n if (stoneCount == 0) {\n emptyCells.add(Cell(rowIndex, columnIndex))\n } else if (stoneCount > 1) {\n twoUpCells.add(Cell(rowIndex, columnIndex, stoneCount))\n }\n }\n }\n\n return moveStone(moves = 0, emptyCells, twoUpCells)\n }\n}\n``` | 0 | 0 | ['Depth-First Search', 'Kotlin'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++, BEAT 100%, PERMUTATION, FAST AND EASY TO UNDERSTAND | c-beat-100-permutation-fast-and-easy-to-dzjv2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe only cells we should think about is the cells less than 1 and cells more than 1.\ | wcf29 | NORMAL | 2024-11-12T00:21:21.373204+00:00 | 2024-11-12T00:21:58.033092+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe only cells we should think about is the cells less than 1 and cells more than 1.\n\nSo, first iterate though entire grid to find **less-than-1 cells** and **more-than-1 cells**, store them to vector less and more.\n\nThan, the problem is simplified to a **permutation-like problem**. For each less-than-1 cell, every more-than-1 cell may fill it. \n\nSo from index-0 in vector less, try every more-than-1 cell to fill it. Finally we can find the minimum move step.\n\nIn addition, we can **pruning** when current step is greater than current minMoves, which significantly reduce the time and leads to **0ms cost.**\n\n# Complexity\n- Time complexity: $O(more!)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(less + more)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nIt\'s a permutation-like problem.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n int minMoves = INT_MAX;\n\n vector<pair<int, int>> less;\n vector<vector<int>> more;\n\n // Find the cell less than 1 and the cell more than 1.\n for (int i = 0; i < 3; ++i) {\n for (int j = 0; j < 3; ++j) {\n if (grid[i][j] == 0) {\n less.emplace_back(i, j);\n } else if (grid[i][j] > 0) {\n more.push_back({i, j, grid[i][j]});\n }\n }\n }\n\n int n = less.size();\n int move = 0;\n\n // A permutation problem.\n // For each less than 1 cell, iterate through all more than 1 to fill it.\n // i is the index of less than 1 cell in vector less.\n auto dfs = [&](auto&& dfs, int i) {\n if (i == n) {\n minMoves = std::min(move, minMoves);\n return;\n }\n if (move >= minMoves) { // Pruning.\n return;\n }\n for (auto &t : more) {\n if (t[2] > 1) {\n t[2] -= 1;\n int stepMove = std::abs(less[i].first - t[0]) +\n std::abs(less[i].second - t[1]);\n move += stepMove;\n dfs(dfs, i + 1);\n move -= stepMove;\n t[2] += 1;\n }\n }\n };\n\n dfs(dfs, 0);\n return minMoves;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | python3 permutations | python3-permutations-by-0icy-hj8b | \n\n# Code\npython3 []\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n req = []\n extra = []\n for r in range | 0icy | NORMAL | 2024-11-03T15:16:56.822555+00:00 | 2024-11-03T15:16:56.822591+00:00 | 7 | false | \n\n# Code\n```python3 []\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n req = []\n extra = []\n for r in range(3):\n for c in range(3):\n if grid[r][c] == 0:\n req.append((r,c))\n elif grid[r][c] > 1:\n extra += [(r,c) for k in range(grid[r][c]-1)]\n\n ans = inf\n for perm in permutations(req):\n total_moves = 0\n for e, s in zip(extra, perm):\n total_moves += abs(e[0]-s[0])+abs(e[1]-s[1])\n ans = min(ans, total_moves)\n \n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Clean code with concise explanation | C++ | clean-code-with-concise-explanation-c-by-adt6 | Approach\n- There would always be a one to one mapping i.e. if there are x(>1) 1\'s in a cell then there would be for sure x-1 cells with 0 who\'re in need of t | Chaitanya_89 | NORMAL | 2024-10-09T15:34:35.041095+00:00 | 2024-10-09T15:39:26.576300+00:00 | 37 | false | # Approach\n- There would always be a one to one mapping i.e. if there are x(>1) 1\'s in a cell then there would be for sure x-1 cells with 0 who\'re in need of these extra ones.\n- Collect the cells who are in deficit and also have extra 1s with\'em\n- Permute all the possible combinations for extra and deficit blanks such that they\'ll have one to one mapping, to get the desired answer \n\nElaboration of 1st point, for one to one mapping.\nAs if there\'s a cell with 4 1\'s in it then there would be definitely be atleast 3 cells with 0 in the grid for sure, as the total number of 1\'s in the grid is fixed(9) and those cells with 0 are gonna get the 1\'s from the ones who have\'em in surplus.\n\n\n# Complexity\n- Time complexity: $$O(8!)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define pi pair<int,int>\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n vector<pi> deficit, extra;\n for(auto i = 0; i < grid.size(); i++){\n for(int j = 0; j < grid[0].size(); j++){\n if(grid[i][j] == 1) continue;\n else if(grid[i][j] == 0) deficit.push_back({i, j});\n else{\n for(int ct = 0; ct < grid[i][j]-1; ct++)\n extra.push_back({i, j});\n }\n }\n }\n int ans = INT_MAX;\n do {\n int temp_ans = 0;\n for(int i = 0; i < extra.size(); i++){\n temp_ans += abs(deficit[i].first - extra[i].first) + \n abs(deficit[i].second - extra[i].second);\n }\n ans = min(ans, temp_ans);\n } while (next_permutation(extra.begin(), extra.end()));\n return ans;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Matrix', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Backtracking (Python) | backtracking-python-by-treerecursion-6kor | Intuition\n Describe your first thoughts on how to solve this problem. \nTransfer stones from givers to receivers. Minimize the number of moves by backtracking | treerecursion | NORMAL | 2024-10-07T15:41:14.008265+00:00 | 2024-10-07T15:41:14.008309+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTransfer stones from givers to receivers. Minimize the number of moves by backtracking.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Index grid cells from top-left to bottom-right. \n2. Scan the grid. If a cell has no stone, append it to the list of receivers; if a cell has more than one stone, append it to the list of givers, alongside the number of extra stones it has to give away. $O(1)$\n3. If the receiver list is empty, all cells have exactly one stone, and no move is required. $O(1)$\n4. Compute shortest distance among cells (`dist`). Cells that share a side are directly connected with distance 1. Compute shortest distance among all other pairs of cells manually or using Floyd-Warshall. $O(1)$\n5. Initialize a list of nine boolean False\'s denoting that none of the receivers has received a stone yet. Initialize `min_cost` as $\\infty$ for final return. Initialize `cost` as a variable storing the number of moves during searching. $O(1)$\n6. Function `give(giver_id, stones_to_give_away)` process the givers list at `giver_id` (or `i` in code), with `stones_to_give_away` (or `stone` in code) stones to give away. (TC analysis below).\n7. If `giver_id == len(givers)`, searching is done, and we simply update `min_cost` if we reach a lower `cost`.\n8. If `stones_to_give_away == 0`, we are done with processing the current `giver_id` and move on to the next giver.\n9. Default value for `stones_to_give_away` is `-1`, meaning that we have just started processing this giver. If this is the case, the number of stones to give away is found in the givers list.\n10. For each receiver in the receivers list, if it has not yet receive a stone, we can attempt to transfer a stone from `giver_id` to it. This transfer incurs `dist[giver_id][reciver]` moves. See the `for` loop within the `give` function for backtracking.\n11. Searching starts with calling `give(0)`. Return `min_cost` once searching is complete.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`give` is called for each giver until it iterates all ways in which the giver may give away all its extra stones. The total number of extra stones is equal to the number of receivers. There can be at most 8 receivers. For an upper bound of TC, matching 8 stones with 8 receivers results in 8!=40,320 permutations. The bound is by no means tight but only to cap the search space so that backtracking is viable.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(1)$\n\n# Code\n```python3 []\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n receivers = []\n givers = []\n for r in range(3):\n for c in range(3):\n if grid[r][c] == 0:\n receivers.append(r * 3 + c)\n elif grid[r][c] > 1:\n givers.append((r * 3 + c, grid[r][c] - 1))\n\n if not receivers: return 0\n\n dist = [[float(\'inf\')] * 9 for _ in range(9)]\n for i in range(9): dist[i][i] = 0\n\n edges = []\n for r in range(3):\n for c in range(3):\n if r < 2: edges.append((r * 3 + c, r * 3 + 3 + c))\n if c < 2: edges.append((r * 3 + c, r * 3 + 1 + c))\n for u, v in edges:\n dist[u][v] = 1\n dist[v][u] = 1\n\n for k in range(9):\n for i in range(9):\n for j in range(9):\n if dist[i][k] != float(\'inf\') and dist[k][j] != float(\'inf\'):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n\n received = [False] * 9\n\n min_cost = 100\n cost = 0\n\n def give(i, stone=-1):\n nonlocal min_cost, cost\n if i == len(givers):\n min_cost = min(min_cost, cost)\n return\n if stone == 0: give(i + 1)\n if stone == -1: stone = givers[i][1]\n u = givers[i][0]\n for v in receivers:\n if received[v]: continue\n received[v] = True\n cost += dist[u][v]\n give(i, stone - 1)\n received[v] = False\n cost -= dist[u][v]\n\n give(0, givers[0][1])\n return min_cost\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | C++ Solution || Brute-Force || Aryan Mittal | c-solution-brute-force-aryan-mittal-by-v-5ksk | \n# Code\ncpp []\nclass Solution {\n\n vector<vector<int>> xtra, zero;\n int ret;\n void solve(int i, int count) {\n // base case\n if(i | Vaibhav_Arya007 | NORMAL | 2024-10-06T20:33:07.172858+00:00 | 2024-10-06T20:33:07.172899+00:00 | 3 | false | \n# Code\n```cpp []\nclass Solution {\n\n vector<vector<int>> xtra, zero;\n int ret;\n void solve(int i, int count) {\n // base case\n if(i >= zero.size()) {\n ret = min(ret, count);\n return;\n }\n for(int k = 0; k < xtra.size(); k++) {\n if(xtra[k][2] == 0) continue;\n xtra[k][2]--;\n solve(i + 1, abs(xtra[k][0] - zero[i][0]) + abs(xtra[k][1] - zero[i][1]) + count);\n xtra[k][2]++;\n }\n }\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n for(int i = 0; i < 3; i++) {\n for(int j = 0; j < 3; j++) {\n if(grid[i][j] == 0)\n zero.push_back({i, j});\n else if(grid[i][j] > 1)\n xtra.push_back({i, j, grid[i][j] - 1});\n }\n }\n if(zero.size() == 0) return 0;\n ret = INT_MAX;\n solve(0, 0);\n return ret;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
reverse-linked-list | [C++] Iterative vs. Recursive Solutions Compared and Explained, ~99% Time, ~85% Space | c-iterative-vs-recursive-solutions-compa-h5tr | Not sure how this problem is expecting me to use less memory than this, but here is the deal:\n we are going to use 3 variables: prevNode, head and nextNode, th | ajna | NORMAL | 2020-08-21T13:11:44.534562+00:00 | 2020-11-03T22:36:07.845278+00:00 | 64,304 | false | Not sure how this problem is expecting me to use less memory than this, but here is the deal:\n* we are going to use 3 variables: `prevNode`, `head` and `nextNode`, that you can easily guess what are meant to represent as we go;\n* we will initialise `prevNode` to `NULL`, while `nextNode` can stay empty;\n* we are then going to loop until our current main iterator (`head`) is truthy (ie: not `NULL`), which would imply we reached the end of the list;\n* during the iteration, we first of all update `nextNode` so that it acquires its namesake value, the one of the next node indeed: `head->next`;\n* we then proceeding "reversing" `head->next` and assigning it the value of `prevNode`, while `prevNode` will become take the current value of `head`;\n* finally, we update `head` with the value we stored in `nextNode` and go on with the loop until we can. After the loop, we return `prevNode`.\n\nI know it is complex, but I find this gif from another platform to make the whole logic much easier to understand (bear in mind we do not need `curr` and will just use `head` in its place):\n\n\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *nextNode, *prevNode = NULL;\n while (head) {\n nextNode = head->next;\n head->next = prevNode;\n prevNode = head;\n head = nextNode;\n }\n return prevNode;\n }\n};\n```\n\nRelatively trivial refactor (the function does basically the same) with recursion and comma operator to make it one-line:\n\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode *head, ListNode *nextNode = NULL, ListNode *prevNode = NULL) {\n return head ? reverseList(head->next, (head->next = prevNode, nextNode), head) : prevNode;\n }\n};\n``` | 1,033 | 4 | ['Linked List', 'C', 'C++'] | 34 |
reverse-linked-list | In-place iterative and recursive Java solution | in-place-iterative-and-recursive-java-so-o2vm | public ListNode reverseList(ListNode head) {\n /* iterative solution */\n ListNode newHead = null;\n while (head != null) {\n Li | braydencn | NORMAL | 2015-05-04T22:18:53+00:00 | 2018-10-23T07:42:21.754521+00:00 | 227,386 | false | public ListNode reverseList(ListNode head) {\n /* iterative solution */\n ListNode newHead = null;\n while (head != null) {\n ListNode next = head.next;\n head.next = newHead;\n newHead = head;\n head = next;\n }\n return newHead;\n }\n \n public ListNode reverseList(ListNode head) {\n /* recursive solution */\n return reverseListInt(head, null);\n }\n \n private ListNode reverseListInt(ListNode head, ListNode newHead) {\n if (head == null)\n return newHead;\n ListNode next = head.next;\n head.next = newHead;\n return reverseListInt(next, head);\n } | 1,030 | 7 | ['Java'] | 70 |
reverse-linked-list | JAVA 0ms 100% Easy Understanding | java-0ms-100-easy-understanding-by-bhanu-92pg | \n\n\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null; \n ListNode current = head;\n \n \n | Bhanu0909 | NORMAL | 2022-10-09T15:26:12.386004+00:00 | 2022-10-13T06:34:37.526655+00:00 | 109,518 | false | \n\n```\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null; \n ListNode current = head;\n \n \n while(current != null) { \n ListNode next = current.next; \n current.next = prev;\n prev = current;\n current = next;\n }\n return prev; \n }\n}\n```\n**WHILE_LOOP EXPLANATION**\n\n\n\n**PLEASE UPVOTE**\nIf you understand the solution\n | 868 | 0 | ['Linked List', 'Java'] | 38 |
reverse-linked-list | Using 2 Methods || Iterative & Recursive || Beats 97.91% | using-2-methods-iterative-recursive-beat-89wo | Intuition\nThe idea is to use three pointers curr, prev, and forward to keep track of nodes to update reverse links.\n Describe your first thoughts on how to so | keshavsharma519 | NORMAL | 2023-02-20T20:45:36.500328+00:00 | 2023-02-20T20:45:36.500367+00:00 | 104,783 | false | # Intuition\nThe idea is to use three pointers curr, prev, and forward to keep track of nodes to update reverse links.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach 1 - using Iterative Method \n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n\n ListNode* prev = NULL;\n ListNode* curr = head;\n\n while(curr != NULL){\n ListNode* forward = curr->next;\n curr->next = prev;\n prev = curr;\n curr = forward;\n \n }\n return prev;\n }\n};\n ```\n# Intuition\nThe idea is to reach the last node of the linked list using recursion then start reversing the linked list.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach 2 - using Recrusion\n\n\n# Complexity\n- Time Complexity: O(N), Visiting over every node one time \n- Auxiliary Space: O(N), Function call stack space\n```\n\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n if(head == NULL || head->next == NULL) return head;\n ListNode* prev = NULL;\n ListNode* h2 = reverseList(head->next);\n head->next->next = head;\n head->next=prev;\n return h2;\n }\n\n};\n```\n\n\n | 704 | 0 | ['C++'] | 16 |
reverse-linked-list | Step By Step Explained with Images. Easiest to understand. Java, C++, Python, JavaScript, Go Codes | step-by-step-explained-with-images-easie-ripe | Intuition\nThis is a basic linked list reversal algorithm. Can be used in various other problems so just understand this one and memorize it.\n\n# Approach\n\n\ | Kunal_Tajne | NORMAL | 2024-08-09T14:29:31.616237+00:00 | 2024-08-22T00:10:09.628517+00:00 | 52,173 | false | # Intuition\nThis is a basic linked list reversal algorithm. Can be used in various other problems so just understand this one and memorize it.\n\n# Approach\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is $$O(n)$$, because we reversed the linked list in a single pass, where \uD835\uDC5B n is the number of nodes in a linked list.\n\n- Space complexity:\nThe space complexity of this solution is $$O(1)$$, because no extra memory is used.\n\n# Algorithm / Pseudo Code\n```\nFunction ReverseList(head)\n Initialize prev to NULL\n Initialize curr to head\n\n While curr is not NULL\n // Save the next node\n next = curr.next\n \n // Reverse the link\n curr.next = prev\n \n // Move prev and curr forward\n prev = curr\n curr = next\n\n // Return the new head of the reversed list\n Return prev\nEnd Function\n```\n\n# Commented Java Code\n```\nclass Solution {\n public ListNode reverseList(ListNode head) {\n // We start with three pointers:\n // 1. prev: This will keep track of the previous node we processed (starts as null).\n // 2. next: This will keep track of the next node to process.\n // 3. curr: This is the current node we are processing (starts as the head of the list).\n ListNode prev = null;\n ListNode next = null;\n ListNode curr = head;\n\n // We loop through the linked list until we reach the end (when curr is null).\n while (curr != null) {\n // Store the next node in the list. We need to do this because we will change the current node\'s next pointer.\n next = curr.next;\n\n // Reverse the link. Instead of pointing to the next node, the current node now points to the previous node.\n curr.next = prev;\n\n // Move the previous pointer to the current node (since the current node is now processed).\n prev = curr;\n\n // Move the current pointer to the next node (to continue processing the rest of the list).\n curr = next;\n }\n\n // When we\'ve processed all nodes, the prev pointer will be at the new head of the reversed list.\n return prev;\n }\n}\n\n```\n# Un-Commented Java Code\n```\nclass Solution {\n public ListNode reverseList(ListNode head) {\n \n ListNode prev = null;\n ListNode next = null;\n ListNode curr = head;\n\n while(curr != null)\n {\n next = curr.next;\n\n curr.next = prev;\n\n prev = curr;\n curr = next;\n }\n\n return prev;\n }\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n // Initialize pointers\n ListNode* prev = nullptr; // Previous node starts as NULL\n ListNode* next = nullptr; // Next node\n ListNode* curr = head; // Current node starts at the head\n\n // Traverse the list\n while (curr != nullptr) {\n // Save the next node\n next = curr->next;\n\n // Reverse the link\n curr->next = prev;\n\n // Move pointers forward\n prev = curr; // Move prev to the current node\n curr = next; // Move curr to the next node\n }\n\n // prev is now the new head of the reversed list\n return prev;\n }\n};\n```\n```python []\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n # Initialize pointers\n prev = None # Previous node starts as None\n curr = head # Current node starts at the head\n\n # Traverse the list\n while curr is not None:\n next_node = curr.next # Save the next node\n \n curr.next = prev # Reverse the link\n \n # Move pointers forward\n prev = curr # Move prev to the current node\n curr = next_node # Move curr to the next node\n\n # prev is now the new head of the reversed list\n return prev\n\n```\n```JavaScript []\nclass Solution {\n reverseList(head) {\n // Initialize pointers\n let prev = null; // Previous node starts as null\n let curr = head; // Current node starts at the head\n\n // Traverse the list\n while (curr !== null) {\n let next = curr.next; // Save the next node\n \n curr.next = prev; // Reverse the link\n \n // Move pointers forward\n prev = curr; // Move prev to the current node\n curr = next; // Move curr to the next node\n }\n\n // prev is now the new head of the reversed list\n return prev;\n }\n}\n```\n\n```Go []\nfunc reverseList(head *ListNode) *ListNode {\n var prev *ListNode // Previous node starts as nil\n curr := head // Current node starts at the head\n\n // Traverse the list\n for curr != nil {\n next := curr.Next // Save the next node\n \n curr.Next = prev // Reverse the link\n \n // Move pointers forward\n prev = curr // Move prev to the current node\n curr = next // Move curr to the next node\n }\n\n // prev is now the new head of the reversed list\n return prev\n}\n```\n\n# A single upvote is all it takes :)\n\nIf found helpful, give a upvote. Keeps me motivated to post more solutions. Thanks! \n\n--------------------------------------------------------------------- | 575 | 1 | ['Linked List', 'Recursion', 'C++', 'Java', 'Go', 'Python3', 'JavaScript'] | 26 |
reverse-linked-list | 【Video】Solution with visualization | video-solution-with-visualization-by-nii-h754 | IntuitionI think the easiest way to understand linked list should be drawing.Solution Video⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️■ Subscribe URL
htt | niits | NORMAL | 2024-11-22T17:20:36.297394+00:00 | 2024-12-27T18:20:50.482325+00:00 | 29,845 | false | # Intuition
I think the easiest way to understand linked list should be drawing.
---
# Solution Video
https://youtu.be/9TsQmdRAxT8
### ⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️
**■ Subscribe URL**
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
Subscribers: 11,092
Thank you for your support!
---
# Approach
I think this is classic algorithm to reverse linked list, so you can use the same idea to other linked list problem.
```
Input: 1 → 2 → 3
```
First of all, we create a new node, let's say `node` initalized with `null`. In the end, this is a return value.
```
node = null
```
Let's see how it works.
```
n h
null 1 → 2 → 3
n is node we initialized
h is head
```
First of all, we keep `head.next`. I'll explain why soon.
```
n h
null 1 → 2 → 3
temp = 2
```
Next, in the end, we can return `3 → 2 → 1 → null`, so `1` will be the last node and next node of `1` should be `null`.
That's why we update `head.next` with `node` we initialized at first, so that we can disconnect the link between `node 1` and `node 2` and connect between `node 1` and `null`.
```
n h
null ← 1 2 → 3
temp = 2
There is no connection between node 1 and node 2 right now.
```
Next, we want node `1` for next node of node `2`, so update `node` we initalized with current `head`
```
n
h
null ← 1 2 → 3
temp = 2
There is no connection between node 1 and node 2 right now.
```
At last, we want to update `head` but problem is **there is no connection between node 1 and node 2 right now.**
That's why `node` we initliazed at fist comes into play. Actually we have `node 2` with `temp`. Just update `head` with `temp`, so that we can move `head` to the next node(= `node 2`), even if we don't have connection between `node 1` and `node 2`.
```
n h
null ← 1 2 → 3
temp = 2
There is no connection between node 1 and node 2 right now.
```
Those are whole process to reverse linked list.
---
⭐️ Points
Step 1, keep `next node` of `head` with `temp`
Step 2, update `head.next` with `node` we initialized
Step 3, update `node` we initialized with `head`
Step 4, update `head` with `temp`
---
I'll speed up.
Step 1
```
n h
null ← 1 2 → 3
temp = 3
There is no connection between node 1 and node 2 right now.
```
Step 2
```
n h
null ← 1 ← 2 3
temp = 3
There is connection between node 1 and node 2.
There is no connection between node 2 and node 3.
```
Step 3
```
n
h
null ← 1 ← 2 3
temp = 3
Now, there is no connection between node 2 and node 3.
```
Step 4
```
n h
null ← 1 ← 2 3
temp = 3
Now, there is no connection between node 2 and node 3.
```
Again, Step 1
```
n h
null ← 1 ← 2 3
temp = null
Now, there is no connection between node 2 and node 3.
```
Step 2
```
n h
null ← 1 ← 2 ← 3 (null)
temp = null
There is connection between node 2 and node 3.
There is no connection between node 3 and (null).
```
Step 3
```
n
h
null ← 1 ← 2 ← 3 (null)
temp = null
There is no connection between node 3 and (null).
```
Step 4
```
n h
null ← 1 ← 2 ← 3 (null)
temp = null
There is no connection between node 3 and (null).
```
Now, `head` is `null`, so we stop iteration. Look at `n` which is initliazed by us. `n` is now `node 3` and `node 3` should be the first node in reversed linked list.
All we have to do is just
```
return node
```
From the node we return, linked list is should be `3 → 2 → 1 → null`. Looks good!
---
https://youtu.be/bU_dXCOWHls
---
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
```python []
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
node = None
while head:
temp = head.next
head.next = node
node = head
head = temp
return node
```
```javascript []
var reverseList = function(head) {
let node = null;
while (head) {
const temp = head.next;
head.next = node;
node = head;
head = temp;
}
return node;
};
```
```java []
class Solution {
public ListNode reverseList(ListNode head) {
ListNode node = null;
while (head != null) {
ListNode temp = head.next;
head.next = node;
node = head;
head = temp;
}
return node;
}
}
```
```C++ []
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* node = nullptr;
while (head != nullptr) {
ListNode* temp = head->next;
head->next = node;
node = head;
head = temp;
}
return node;
}
};
```
## Step by step Algorithm
1. **Initialization**:
- We start by initializing a variable `node` to `None`. This variable will eventually become the new head of the reversed linked list.
```python
node = None
```
2. **Traversal and Reversal**:
- We enter a `while` loop where we iterate through each node of the original linked list, starting from the head (`head`).
```python
while head:
```
- Within the loop, we first store the next node of the current node (`head`) in a temporary variable `temp`. This is crucial because we will be modifying the `next` pointer of the current node, which will otherwise result in losing access to the next node.
```python
temp = head.next
```
- Then, we update the `next` pointer of the current node (`head`) to point to the `node`, effectively reversing the direction of the pointer.
```python
head.next = node
```
- After updating the `next` pointer of the current node, we move the `node` pointer to the current node. This essentially builds the reversed linked list incrementally.
```python
node = head
```
- Finally, we move the `head` pointer to the next node (`temp`), effectively advancing to the next node in the original linked list.
```python
head = temp
```
3. **Termination**:
- We continue this process until we have traversed the entire original linked list (`head` becomes `None`), at which point we exit the `while` loop.
4. **Return**:
- We return the `node` pointer, which now points to the new head of the reversed linked list.
```python
return node
```
---
# Solution 2 - Recursive Solution
I didn't realize there was a follow-up question when I solved this question, so here's the code for the recursive solution:
```python []
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
```
```javascript []
var reverseList = function(head) {
if (!head || !head.next) {
return head;
}
var newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
};
```
```java []
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
```
```C++ []
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
```
---
Thank you for reading my post.
## ⭐️ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
https://youtu.be/8feKVQcOs28 | 499 | 2 | ['C++', 'Java', 'Python3', 'JavaScript'] | 4 |
reverse-linked-list | Python Iterative and Recursive Solution | python-iterative-and-recursive-solution-aoc9g | class Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def reverseList(self, head):\n prev = None\n while head:\n | tusizi | NORMAL | 2015-05-16T11:51:19+00:00 | 2018-10-26T20:48:55.044010+00:00 | 116,596 | false | class Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def reverseList(self, head):\n prev = None\n while head:\n curr = head\n head = head.next\n curr.next = prev\n prev = curr\n return prev\n\n\nRecursion\n\n class Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def reverseList(self, head):\n return self._reverse(head)\n\n def _reverse(self, node, prev=None):\n if not node:\n return prev\n n = node.next\n node.next = prev\n return self._reverse(n, node) | 433 | 1 | [] | 42 |
reverse-linked-list | Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Recursive & Iterative) | easy-0-ms-100-fully-explained-java-c-pyt-dunr | Java Solution (Recursive Approach):\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List.\n\nclass Solution {\n public List | PratikSen07 | NORMAL | 2022-08-21T11:00:27.581173+00:00 | 2022-08-31T12:14:18.009397+00:00 | 96,035 | false | # **Java Solution (Recursive Approach):**\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List.\n```\nclass Solution {\n public ListNode reverseList(ListNode head) {\n // Special case...\n if (head == null || head.next == null) return head;\n // Create a new node to call the function recursively and we get the reverse linked list...\n ListNode res = reverseList(head.next);\n // Set head node as head.next.next...\n head.next.next = head;\n //set head\'s next to be null...\n head.next = null;\n return res; // Return the reverse linked list...\n }\n}\n```\n\n# **C++ Solution (Iterative Approach):**\n```\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n // Special case...\n if(head == NULL || head->next == NULL) return head;\n // Initialize prev pointer as the head...\n ListNode* prev = head;\n // Initialize curr pointer as the next pointer of prev...\n ListNode* curr = prev->next;\n // Initialize next of head pointer as NULL...\n head->next = NULL;\n // Run a loop till curr and prev points to NULL...\n while(prev != NULL && curr != NULL){\n // Initialize next pointer as the next pointer of curr...\n ListNode* next = curr->next;\n // Now assign the prev pointer to curr\u2019s next pointer.\n curr->next = prev;\n // Assign curr to prev, next to curr...\n prev = curr;\n curr = next;\n }\n return prev; // Return the prev pointer to get the reverse linked list...\n }\n};\n```\n\n# **Python Solution (Iterative Approach):**\nRuntime: 18 ms, faster than 97.75% of Python online submissions for Reverse Linked List.\n```\nclass Solution(object):\n def reverseList(self, head):\n # Initialize prev pointer as NULL...\n prev = None\n # Initialize the curr pointer as the head...\n curr = head\n # Run a loop till curr points to NULL...\n while curr:\n # Initialize next pointer as the next pointer of curr...\n next = curr.next\n # Now assign the prev pointer to curr\u2019s next pointer.\n curr.next = prev\n # Assign curr to prev, next to curr...\n prev = curr\n curr = next\n return prev # Return the prev pointer to get the reverse linked list...\n```\n \n# **JavaScript Solution (Recursive Approach):**\n```\nvar reverseList = function(head) {\n // Special case...\n if (head == null || head.next == null) return head;\n // Create a new node to call the function recursively and we get the reverse linked list...\n var res = reverseList(head.next);\n // Set head node as head.next.next...\n head.next.next = head;\n //set head\'s next to be null...\n head.next = null;\n return res; // Return the reverse linked list...\n};\n```\n\n# **C Language (Iterative Approach):**\n```\nstruct ListNode* reverseList(struct ListNode* head){\n // Special case...\n if(head == NULL || head->next == NULL) return head;\n // Initialize prev pointer as the head...\n struct ListNode* prev = head;\n // Initialize curr pointer as the next pointer of prev...\n struct ListNode* curr = prev->next;\n // Initialize next of head pointer as NULL...\n head->next = NULL;\n // Run a loop till curr and prev points to NULL...\n while(prev != NULL && curr != NULL){\n // Initialize next pointer as the next pointer of curr...\n struct ListNode* next = curr->next;\n // Now assign the prev pointer to curr\u2019s next pointer.\n curr->next = prev;\n // Assign curr to prev, next to curr...\n prev = curr;\n curr = next;\n }\n return prev; // Return the prev pointer to get the reverse linked list...\n}\n```\n\n# **Python3 Solution (Iterative Approach):**\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # Initialize prev pointer as NULL...\n prev = None\n # Initialize the curr pointer as the head...\n curr = head\n # Run a loop till curr points to NULL...\n while curr:\n # Initialize next pointer as the next pointer of curr...\n next = curr.next\n # Now assign the prev pointer to curr\u2019s next pointer.\n curr.next = prev\n # Assign curr to prev, next to curr...\n prev = curr\n curr = next\n return prev # Return the prev pointer to get the reverse linked list...\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 406 | 2 | ['Linked List', 'Recursion', 'C', 'Iterator', 'Python', 'Java', 'Python3', 'JavaScript'] | 21 |
reverse-linked-list | C++ Iterative and Recursive | c-iterative-and-recursive-by-jianchao-li-1t8q | Well, since the head pointer may also be modified, we create a pre that points to it to facilitate the reverse process.\n\nFor the example list 1 -> 2 -> 3 -> 4 | jianchao-li | NORMAL | 2015-07-06T07:27:59+00:00 | 2018-10-25T09:58:09.969754+00:00 | 92,581 | false | Well, since the `head` pointer may also be modified, we create a `pre` that points to it to facilitate the reverse process.\n\nFor the example list `1 -> 2 -> 3 -> 4 -> 5` in the problem statement, it will become `0 -> 1 -> 2 -> 3 -> 4 -> 5` (we init `pre -> val` to be `0`). We also set a pointer `cur` to `head`. Then we keep inserting `cur -> next` after `pre` until `cur` becomes the last node. This idea uses three pointers (`pre`, `cur` and `temp`). You may implement it as follows.\n\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *pre = new ListNode(0), *cur = head;\n pre -> next = head;\n while (cur && cur -> next) {\n ListNode* temp = pre -> next;\n pre -> next = cur -> next;\n cur -> next = cur -> next -> next;\n pre -> next -> next = temp;\n }\n return pre -> next;\n }\n};\n```\n\nOr\n\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *pre = new ListNode(0), *cur = head;\n pre -> next = head;\n while (cur && cur -> next) {\n ListNode* temp = cur -> next;\n cur -> next = temp -> next;\n temp -> next = pre -> next;\n pre -> next = temp;\n }\n return pre -> next;\n }\n};\n```\n\nWe can even use fewer pointers. The idea is to reverse one node at a time from the beginning of the list.\n\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* cur = NULL;\n while (head) {\n ListNode* next = head -> next;\n head -> next = cur;\n cur = head;\n head = next;\n }\n return cur;\n }\n};\n```\n\nAll the above solutions are iterative. A recursive one is as follows. First reverse all the nodes after `head`. Then we need to set `head` to be the final node in the reversed list. We simply set its next node in the original list (`head -> next`) to point to it and sets its `next` to `NULL`. \n\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n if (!head || !(head -> next)) {\n return head;\n }\n ListNode* node = reverseList(head -> next);\n head -> next -> next = head;\n head -> next = NULL;\n return node;\n }\n};\n``` | 356 | 7 | ['Linked List', 'Recursion', 'Iterator', 'C++'] | 47 |
reverse-linked-list | My Java recursive solution | my-java-recursive-solution-by-caodanbobo-qr9t | public class Solution {\n public ListNode reverseList(ListNode head) {\n if(head==null || head.next==null)\n return head;\n | caodanbobo | NORMAL | 2015-06-18T01:46:43+00:00 | 2018-10-24T10:47:28.662420+00:00 | 46,972 | false | public class Solution {\n public ListNode reverseList(ListNode head) {\n if(head==null || head.next==null)\n return head;\n ListNode nextNode=head.next;\n ListNode newHead=reverseList(nextNode);\n nextNode.next=head;\n head.next=null;\n return newHead;\n }\n } | 147 | 4 | ['Java'] | 17 |
reverse-linked-list | Javascript ES6 less code solution | javascript-es6-less-code-solution-by-sal-emzg | \nvar reverseList = function(head) {\n let [prev, current] = [null, head]\n while(current) {\n [current.next, prev, current] = [prev, current, curr | saltant | NORMAL | 2019-06-17T09:13:30.528452+00:00 | 2019-06-17T09:16:28.253051+00:00 | 14,318 | false | ```\nvar reverseList = function(head) {\n let [prev, current] = [null, head]\n while(current) {\n [current.next, prev, current] = [prev, current, current.next]\n }\n return prev\n}\n``` | 127 | 2 | ['JavaScript'] | 16 |
reverse-linked-list | Python solution - Simple Iterative | python-solution-simple-iterative-by-giri-hpqe | I'm not sure if it's already posted here, but this is simple iterative approach. The idea is to change next with prev, prev with current, and current with next. | girikuncoro | NORMAL | 2015-09-11T23:19:19+00:00 | 2015-09-11T23:19:19+00:00 | 30,909 | false | I'm not sure if it's already posted here, but this is simple iterative approach. The idea is to change next with prev, prev with current, and current with next.\n\n def reverseList(self, head):\n prev = None\n curr = head\n\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n \n return prev | 120 | 2 | ['Iterator', 'Python'] | 11 |
reverse-linked-list | 0ms 100% ||✅Step By Step Visualization. Easiest to understand. Java, C++, Python, | java-0ms-100-step-by-step-explained-with-kgvz | ✅IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END😊 ✅Intuition💡:Iterative Approach:
Use two pointers: prev (starts as null) and curr (starts at head).
At each | Varma5247 | NORMAL | 2025-03-18T06:38:08.286741+00:00 | 2025-04-08T05:31:42.381068+00:00 | 7,767 | false | ✅**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END**😊 ✅
# Intuition💡:
### **Iterative Approach:**
- Use two pointers: ```prev``` (starts as ```null```) and ```curr``` (starts at ```head```).
- At each step:
1 . Store ```curr.next``` in ```temp```.
2 . Reverse ```curr.next``` to point to ```prev```.
3 . Move ```prev``` to ```curr``` and ```curr``` to ```temp```.
- Repeat until ```curr``` is ```null```.
- ```prev``` becomes the new head of the reversed list.
### **Visualization:**
- Original list : ```1 -> 2 -> 3 -> 4 -> 5 ->null```
- Reversed list : ```5 -> 4 -> 3 -> 2 -> 1 -> null```
___
# Approach & Step-by-Step Visualization🔍:
<!-- Describe your approach to solving the problem. -->
1 . ```prev = null```:
- prev starts as null because there’s no node before the head.
2 . ```curr = head```:
- curr points to the first node (head) of the list.

___
## **Step 1: Save the Next Node**
- **Code:**
```ListNode temp = curr.next;```
- **Action:** Save the next node of curr in a temporary variable temp.
- **Visualization:**
```
curr -> 1
temp -> 2
```

___
## **Step 2: Reverse the Link**
- **Code:** ```curr.next = prev;```
- **Action:** Reverse the link of curr to point to prev.
- **Visualization:**
```null <- 1 2 -> 3 -> 4 -> 5 -> null```

___
### **Step 3: Move** ```prev``` **to** ```curr```
- **Code:** ```prev = curr```;
- **Action:** Move ```prev``` to the current node (```curr```).
- **Visualization:**
```
prev -> 1
curr -> 1
temp -> 2
```

___
## **Step 4: Move** ```curr``` **to** ```temp```
- **Code:** ```curr = temp;```
- **Action:** Move ```curr``` to the next node (saved in ```temp```).
- **Visualization:**
```
prev -> 1
curr -> 2
temp -> 2
```

___
## **Step 5: Next Iteration - Save Next Node**
- **Code:** ```ListNode temp = curr.next;```
- **Action:** Save the next node of ```curr``` in ```temp``` for the next reversal step.
- **Visualization:**
```
curr -> 2
temp -> 3
prev -> 1
```

___
## **Step 6: Reverse the Link**
- **Code:** ```curr.next = prev;```
- **Action**: Reverse the link of ```curr``` to point to ```prev```.
- **Visualization:**
```
null <- 1 <- 2 3 -> 4 -> 5 -> null
```

___
## **Final State (After All Iterations)**
- **Code:** ```return prev;```
- **Action:** Return ```prev```, which is now the new head of the reversed list.
- **Visualization:**
```
Reversed Linked List: 5 -> 4 -> 3 -> 2 -> 1 -> null
```

- **Result:** The original ```list 1 -> 2 -> 3 -> 4 -> 5 -> null``` is now reversed to ```5 -> 4 -> 3 -> 2 -> 1 -> null```.
___
# ⏳Complexity Analysis
- Time complexity: $$O(n)$$ (linear time).
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(1)$$ (constant space).
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
___
# 💻Code Implementation
```java []
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev=null;
ListNode curr=head;
while(curr!=null){
ListNode temp=curr.next; //step1
curr.next=prev; //step2
prev = curr; //step3
curr=temp; //step4
}
return prev;
}
}
```
```c++ []
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* temp = curr->next; // Store the next node
curr->next = prev; // Reverse the current node's pointer
prev = curr; // Move prev to current node
curr = temp; // Move to the next node
}
return prev; // New head of the reversed list
}
};
```
```python []
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def reverseList(self, head):
prev = None # Initialize prev as None
curr = head # Start with curr at the head of the list
while curr:
temp = curr.next # Store the next node
curr.next = prev # Reverse the pointer
prev = curr # Move prev forward
curr = temp # Move curr forward
return prev # prev is the new head of the reversed list
```
**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
🔼 **Please Upvote**
```
✨ AN UPVOTE WILL BE APPRECIATED ^_~ ✨
```
**🎯If you are a beginner solve these problem which makes concepts clear for future coding :**
$$1$$ . [1. Two Sum](https://leetcode.com/problems/two-sum/solutions/6611819/step-by-step-visualization-beginner-frei-5ch1/)
$$2$$ . [26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/6608214/beginner-freindlyvisualizationjavacpytho-5lil/)
$$3$$ . [141 . Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/solutions/6556606/0ms-100-step-by-step-explained-with-visu-fpe6/)
$$4$$ . [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/solutions/6550282/java-0ms-100-step-by-step-explained-with-kgvz/)
$$5$$ . [1863. Sum of All Subset XOR Totals (Bit Manipulation)](https://leetcode.com/problems/sum-of-all-subset-xor-totals/solutions/6616852/step-by-step-visualization-beginner-frei-5qev/)
$$6$$ . [2529. Maximum Count of Positive Integer and Negative Integer (Binary Search)](https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/solutions/6526081/binary-search-beginner-freindlyvisualiza-smsf/)

| 106 | 3 | ['Linked List', 'Two Pointers', 'Iterator', 'Python', 'C++', 'Java', 'Python3'] | 7 |
reverse-linked-list | 🔥✅✅ Beat 100% | 0 ms ✅✅🔥 | beat-100-0-ms-by-devogabek-fnpq | UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE \n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPV | DevOgabek | NORMAL | 2024-03-21T00:09:40.977626+00:00 | 2024-03-21T12:28:40.879101+00:00 | 26,696 | false | # UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE \n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n# UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE UPVOTE\n\n\n\n[](https://leetcode.com/problems/reverse-linked-list/submissions/1209548454?envType=daily-question&envId=2024-03-21)\n\n# Explanation creating\n```python []\nclass Solution(object):\n def reverseList(self, head):\n prev_node = None\n current_node = head\n\n while current_node is not None:\n next_node = current_node.next\n current_node.next = prev_node\n prev_node = current_node\n current_node = next_node\n\n return prev_node\n```\n```python3 []\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev_node = None\n current_node = head\n\n while current_node is not None:\n next_node = current_node.next\n current_node.next = prev_node\n prev_node = current_node\n current_node = next_node\n\n return prev_node\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* curr = head;\n while (curr != nullptr) {\n ListNode* nextTemp = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n }\n};\n```\n```javascript []\nvar reverseList = function(head) {\n let prev = null;\n let curr = head;\n while (curr !== null) {\n let nextTemp = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n};\n```\n\n | 81 | 9 | ['Linked List', 'Recursion', 'Python', 'C++', 'Python3', 'JavaScript'] | 18 |
reverse-linked-list | Detailed explanation of recursive solution + alternate simpler recursive solution | detailed-explanation-of-recursive-soluti-163y | For anyone still trying to understand the recursive solution, here\'s the step by step explanation, considering the example given in the question:\n\n1 -> 2 -> | anirudhgoel | NORMAL | 2022-01-23T03:56:52.716590+00:00 | 2022-01-23T03:56:52.716618+00:00 | 8,425 | false | For anyone still trying to understand the recursive solution, here\'s the step by step explanation, considering the example given in the question:\n\n`1 -> 2 -> 3 -> 4 -> 5`\n\nFor the first 4 calls of the `reverseList` function, we just go into the call stack, as the base case is not hit. When we call the function for the 5th time, that is, `reverseList(5)`, we reach the base case as `5.next == null`, so we return at this point to the 4th call in the stack, that is, `reverseList(4)`. Now, for this 4th node, p is set equal to the returned value (5th node) and essentially this is the only time p gets updated in the whole solution. After this point, p\'s value is just passed across stack calls so that it can be returned as the new head.\nBack to the next line in the 4th stack call, `head.next.next = head`. This line simply means, make the `next node` of the `current node`, point to the `current node`. So, `5.next` is set equal to 4th node.\nNext line says, `head.next = null` and this seems a bit confusing but it really isn\'t. This line has no significance for any other node except the (new) last one, that is, for the node containing `1` as value. This statement is just used to set the value of `1.next` as `null`. For all other nodes, this line means nothing as it gets overwritten as we move back further in the call stack. Let\'s understand by going further in the example:\nSo, at this point, we have `p = 5`, `5.next = 4`, `4.next = null`, and now we move back in the call stack to `reverseList(3)`. Here again we have `head.next.next = head`, which basically means, `4.next = 3`. So you see, the `head.next = null` had no impact on the 4th node as it was updated in the next call. Going forward in a similar manner, you will observe, the value set by `head.next = null` gets overwritten for every node except for the first one, where there\'s no next call to update it, which mean, `1.next = null`, which is what we want in the final linked list.\nLastly, every stack call returns `p` which was just set in the last call when we were going in (`p = 5`) and as I said before, it doesn\'t get updated in any call after that, so it just serves to return the new head of the reversed list.\n\nHope this makes it clearer for you. If you still find the recursive solution difficult to understand, I have an alternative recursive solution which uses 2 variables as a substitute to `head.next.next`, which may seem easier:\n\n```\nclass Solution:\n def flipMapping(self, curr, nex):\n if nex.next:\n self.flipMapping(curr.next, nex.next)\n else:\n self.new_head = nex\n \n nex.next = curr\n \n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n \n self.new_head = None \n self.flipMapping(head, head.next) \n head.next = None \n return(self.new_head)\n``` | 74 | 0 | ['Recursion', 'Python'] | 6 |
reverse-linked-list | Python Iterative & Recursive | python-iterative-recursive-by-wangqiuc-swx1 | To reverse a linked list, we actually reverse the direction of every next pointer. \nFor example, we reverse a linked list 1->2->3->4->5 by changing every -> to | wangqiuc | NORMAL | 2019-03-02T00:11:10.653830+00:00 | 2019-08-14T04:43:54.039912+00:00 | 7,321 | false | To reverse a linked list, we actually reverse the direction of every next pointer. \nFor example, we reverse a linked list 1->2->3->4->5 by changing every -> to <- and get the result as 1<-2<-3<-4<-5. And we need to return the pointer to 5 instead of to 1.\nTo solve it efficiently, we can do it in one loop iteration or recursion.\n\nFor iteration, we create a ListNode **rev** to keep track of what we have reversed otherwise we would lose it. Then we iterate linked list and make **head** point to the current node. We change a -> to <- by calling **head.next = rev**, update rev by calling **rev = head**, move to next node by calling **head = head.next**. To save a temporary variable, we could assign these variables **in one line**, but **head.next** and **rev** should be updated before **head** is updated otherwise direction would not be reversed and **rev** would keep pointing to itself.\nFor example, 1->2->3, 1 is current node **head,** what we have reversed **rev** is None, 2 is **head.next**. Calling **head.next = rev** leads to **None<-1**. Calling **head = head.next** concurrently to make head pointing to 2->3. Updating rev as **1->None**. And in next iteration, we will change 2->3 to 1<-2 and keep changing -> to <- so on so forth.\n```\ndef reverseListIter(head):\n\trev = None\n\twhile head: \n\t\thead.next, rev, head = rev, head, head.next\n\treturn rev\n```\nFor recursion, the bottom layer is the end of the origin linked list so we just return it. For the outer layer, for example, 4->5, we change -> to <- by calling **head.next.next = head** where **head** points at 4 and **head.next** points at 5. **node**, which is **self.reverseList(head.next)** also points at 5 or 5->4, is what we need to return in this layer. So when we keep returning to the outer layer, reversed linked list keep growing (a -> b becomes a <- b as **head.next.next = head**)\nAnother example, in some recursion, you have linked list **1->2->3->null**, reversed linked list **5->4->3->null**. **head** points at **2**, **head.next** points at **3**, **5->4->3->null** is what you have reversed and stored in **node=reversedList(head.next)**. Now you need to place 2 to the end of 5->4->3. So you call **head.next.next = head** or **3.next = 2**, and **head.next = null** or **2.next = null**. Then you have original linked list **1->2->null**, and reversed linked list (head node 5 stored in **node**) **5->4->3->2->null**. Then you return these to outer recursion.\n```\ndef reverseListRecu(head):\n\tif not head or not head.next: return head\n\tnode, head.next.next, head.next = reverseListRecu(head.next), head, None\n\treturn node\n```\nOne thing should be notice that we should always be fully aware of what a variable points at. The **rev** and **reverseList_Recu(node)** point at the head of the reversed linked list while the current node **head** that we are visiting in origin linked list point at the tail of the reversed linked list.\nBoth methods take a liner scan without extra space. So time complexity is O(n) and space is O(1). | 69 | 3 | [] | 5 |
reverse-linked-list | ✅Best Method 🔥 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | best-method-100-c-java-python-beginner-f-d5s2 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe given code snippet implements the iterative approach to reverse a linked list. The | rahulvarma5297 | NORMAL | 2023-06-10T05:08:04.918036+00:00 | 2023-06-10T05:12:20.599697+00:00 | 4,873 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code snippet implements the iterative approach to reverse a linked list. The intuition behind it is to use three pointers: `prev`, `head`, and `nxt`. By reversing the pointers between the nodes, we can reverse the linked list.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a pointer `prev` and initialize it to `NULL`. This pointer will initially be the new end of the reversed linked list.\n2. Start iterating through the linked list with a pointer `head`.\n3. Inside the loop, create a pointer `nxt` and assign it the next node after `head`. This pointer is used to store the next node temporarily.\n4. Reverse the pointer direction of `head` by setting `head->next` to `prev`. This step effectively reverses the direction of the current node.\n5. Move the `prev` pointer to `head` and update `head` to `nxt` for the next iteration.\n6. Repeat steps 3-5 until the end of the linked list is reached (i.e., `head` becomes `NULL`).\n7. Return `prev`, which will be the new head of the reversed linked list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* prev = NULL;\n\n while(head) {\n ListNode* nxt = head->next;\n head->next = prev;\n prev = head;\n head = nxt;\n }\n return prev;\n }\n};\n```\n```Java []\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n\n while (head != null) {\n ListNode nxt = head.next;\n head.next = prev;\n prev = head;\n head = nxt;\n }\n\n return prev;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n prev = None\n\n while head:\n nxt = head.next\n head.next = prev\n prev = head\n head = nxt\n\n return prev\n```\n\n\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n | 63 | 0 | ['Linked List', 'C++', 'Java', 'Python3'] | 6 |
reverse-linked-list | Easy to understand recursive solution ( beats 98% , takes 2 arguments ) | easy-to-understand-recursive-solution-be-ws30 | Each call goes something like this : \n1->2->3 to 3->2->1\n\n(1, null ) :\nnext =2 ;\n1->next = null;\nreturn (2,1)\n\n(2, 1)\nnext = 3;\n2->next = 1;\nreturn ( | spooja__ | NORMAL | 2019-11-30T14:40:34.287811+00:00 | 2020-08-14T16:09:59.189673+00:00 | 8,398 | false | Each call goes something like this : \n1->2->3 to 3->2->1\n\n(1, null ) :\nnext =2 ;\n1->next = null;\nreturn (2,1)\n\n(2, 1)\nnext = 3;\n2->next = 1;\nreturn (3,2)\n\n(3,2)\nnext = null;\n3->next = 2;\nreturn (null, 3)\n\n(null, 3)\nreturn 3; **( the new head node )**\n\n```\n ListNode* helper(ListNode* head, ListNode* prev) {\n if (!head) return prev;\n ListNode* next = head->next;\n head->next = prev;\n return helper(next, head);\n \n \n }\n \n ListNode* reverseList(ListNode* head) { \n return helper (head, NULL);\n \n } | 55 | 1 | ['Recursion', 'C', 'C++'] | 3 |
reverse-linked-list | Javascript Iterative and Recursive solution | javascript-iterative-and-recursive-solut-8gw5 | My Javascript solution based on Back To Back SWE\n\n## Iterative\n- Time: O(n)\n- Space: O(1)\n\njsx\nvar reverseList = function(head) {\n let prev = null\n | roy6234leetcode | NORMAL | 2020-09-29T06:07:20.207387+00:00 | 2020-09-29T06:10:29.872742+00:00 | 7,616 | false | My Javascript solution based on [Back To Back SWE](https://www.youtube.com/watch?v=O0By4Zq0OFc&feature=youtu.be)\n\n## Iterative\n- Time: O(n)\n- Space: O(1)\n\n```jsx\nvar reverseList = function(head) {\n let prev = null\n let curr = head\n let next = null\n \n while(curr!== null){\n // save next\n next = curr.next\n // reverse\n curr.next = prev\n // advance prev and curr\n prev = curr\n curr = next\n }\n return prev;\n};\n```\n\n## ES6 code\n```\nvar reverseList = function(head) {\n let [prev, current] = [null, head]\n while(current) {\n [current.next, prev, current] = [prev, current, current.next]\n }\n return prev\n}\n```\n\n### Recursive\n\n- Time: O(n)\n- Space: O(n)\n\n```jsx\nvar reverseList = function(head) {\n\t// base case\n if (head == null || head.next == null){\n return head;\n }\n\t// go all the way to the end\n let reversedListHead = reverseList(head.next)\n\t// add reverse myself\n head.next.next = head;\n head.next = null;\n\t// go up\n return reversedListHead\n};\n``` | 51 | 0 | ['Recursion', 'Iterator', 'JavaScript'] | 10 |
reverse-linked-list | ✔️Full Explanation ✔️Python ✔️C++ ✔️Java ✔️C# ✔️Go | full-explanation-python-c-java-c-go-by-o-csz5 | Explanation\n- We initialize three pointers: prev, current, and next.\n- prev will initially be nullptr because it will be the new tail of the reversed list.\n- | otabek_kholmirzaev | NORMAL | 2024-03-21T00:19:09.118222+00:00 | 2024-03-21T17:07:57.957060+00:00 | 3,010 | false | # Explanation\n- We initialize three pointers: **prev**, **current**, and **next**.\n- **prev** will initially be **nullptr** because it will be the new tail of the reversed list.\n- **current** starts from the head of the original list.\n- Inside the loop, we:\n - Store the next node of **current** in the variable **next**.\n - Reverse the link of **current** to point it to **prev**.\n - Move **prev**, **current**, and **next** pointers one step ahead.\n- After the loop, **prev** points to the new head of the reversed list.\n- Return **prev**.\n\n# Complexity\n- Time complexity: O(n) - We traverse the list once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) - We only use a constant amount of extra space for the three pointers, regardless of the size of the list.\n\n# Code\n``` cpp []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *prev = nullptr;\n ListNode *current = head;\n ListNode *next = nullptr;\n \n while (current != nullptr) {\n next = current->next; // Save the next node\n current->next = prev; // Reverse the link\n prev = current; // Move pointers one position ahead\n current = next;\n }\n \n // \'prev\' now points to the new head of the reversed list\n return prev;\n }\n};\n```\n``` python []\nclass Solution:\n def reverseList(self, head):\n prev = None\n current = head\n \n while current:\n next_node = current.next # Save the next node\n current.next = prev # Reverse the link\n prev = current # Move pointers one position ahead\n current = next_node\n \n # \'prev\' now points to the new head of the reversed list\n return prev\n```\n``` java []\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode current = head;\n \n while (current != null) {\n ListNode nextNode = current.next; // Save the next node\n current.next = prev; // Reverse the link\n prev = current; // Move pointers one position ahead\n current = nextNode;\n }\n \n // \'prev\' now points to the new head of the reversed list\n return prev;\n }\n}\n```\n``` csharp []\npublic class Solution {\n public ListNode ReverseList(ListNode head) {\n ListNode prev = null;\n ListNode current = head;\n ListNode nextNode = null;\n \n while (current != null) {\n nextNode = current.next; // Save the next node\n current.next = prev; // Reverse the link\n prev = current; // Move pointers one position ahead\n current = nextNode;\n }\n \n // \'prev\' now points to the new head of the reversed list\n return prev;\n }\n}\n```\n``` Go []\nfunc reverseList(head *ListNode) *ListNode {\n var prev, current, nextNode *ListNode\n current = head\n \n for current != nil {\n nextNode = current.Next // Save the next node\n current.Next = prev // Reverse the link\n prev = current // Move pointers one position ahead\n current = nextNode\n }\n \n // \'prev\' now points to the new head of the reversed list\n return prev\n}\n```\n\n | 49 | 0 | ['Python', 'C++', 'Java', 'Go', 'C#'] | 3 |
reverse-linked-list | Accepted C Solutions both iteratively and recursively | accepted-c-solutions-both-iteratively-an-nqgg | struct ListNode* reverseList(struct ListNode* head) {\n \tif(NULL==head) return head;\n \n \tstruct ListNode *p=head;\n \tp=head->next;\n \thead- | redace85 | NORMAL | 2015-05-05T11:03:57+00:00 | 2015-05-05T11:03:57+00:00 | 12,152 | false | struct ListNode* reverseList(struct ListNode* head) {\n \tif(NULL==head) return head;\n \n \tstruct ListNode *p=head;\n \tp=head->next;\n \thead->next=NULL;\n \twhile(NULL!=p){\n \t\tstruct ListNode *ptmp=p->next;\n \t\tp->next=head;\n \t\thead=p;\n \t\tp=ptmp;\n \t}\n \treturn head;\n }\n\n\nabove is the iterative one. simple, nothing to explain.\n----------\n\n\n struct ListNode* reverseListRe(struct ListNode* head) {\n \tif(NULL==head||NULL==head->next) return head;\n \n \tstruct ListNode *p=head->next;\n \thead->next=NULL;\n \tstruct ListNode *newhead=reverseListRe(p);\n \tp->next=head;\n \n \treturn newhead;\n }\n\nabove is the recursively one.Both are accepted.\n---------- | 49 | 0 | [] | 2 |
reverse-linked-list | Simple Iterative & Recursive Solution With Diagram (beats 100%) | simple-iterative-recursive-solution-with-lxud | Iterative\n\n\n\nfunc reverseList(head *ListNode) *ListNode {\n if head == nil {\n return nil\n }\n \n var revHead *ListNode\n\n for head | mayankagarwal2402 | NORMAL | 2022-11-13T05:58:21.150014+00:00 | 2023-09-18T11:13:51.201734+00:00 | 3,826 | false | # **Iterative**\n\n\n```\nfunc reverseList(head *ListNode) *ListNode {\n if head == nil {\n return nil\n }\n \n var revHead *ListNode\n\n for head != nil {\n tmp := head.Next\n head.Next = revHead\n revHead = head\n head = tmp\n }\n return revHead\n}\n```\n\n\n*same logic, lesser code :*\n```\nfunc reverseList(head *ListNode) *ListNode {\n var revHead *ListNode\n for head != nil {\n head.Next, revHead, head = revHead, head, head.Next\n }\n return revHead\n}\n```\n\n# **Recursive**\n\n\n\n```\nfunc reverseList(head *ListNode) *ListNode {\n if head == nil {\n return nil\n }\n rev, _ := reverse(head)\n return rev\n}\n\nfunc reverse(head *ListNode) (root, tail *ListNode) {\n root, tail = head, head \n\t\n if head.Next != nil { \n root, tail = reverse(head.Next) \n head.Next = nil \n tail.Next = head \n tail = head \n }\n \n return root, tail \n}\n```\n\n*lesser code, but complex:*\n```\nfunc reverseList(head *ListNode) *ListNode {\n revHead := head\n\n if head != nil && head.Next != nil {\n revHead = reverseList(head.Next)\n head.Next.Next = head\n head.Next = nil\n }\n\n return revHead\n}\n```\n\n#### PS: Please upvote if you liked the explanatoin and appreciate my effort, helps it reaching others who need it. Thanks :)\nStay motivated. \n\n\n | 43 | 0 | ['Go'] | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.