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
cut-off-trees-for-golf-event
[Python3] min heap + BFS
python3-min-heap-bfs-by-reniclin-rmv3
\n# Min Heap + BFS\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n # 1. use min heap to sort the tree by height\n he
reniclin
NORMAL
2022-04-03T06:10:47.859878+00:00
2022-04-03T06:10:47.859925+00:00
982
false
```\n# Min Heap + BFS\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n # 1. use min heap to sort the tree by height\n heap = []\n for r in range(len(forest)):\n for c in range(len(forest[0])):\n if forest[r][c] > 1:\n heapq.heappush(heap, (forest[r][c], r, c))\n\n totalSteps, currR, currC = 0, 0, 0\n while heap:\n height, r, c = heapq.heappop(heap)\n steps = self.bfsGetMinSteps(forest, currR, currC, r, c)\n if steps == -1:\n return -1\n currR, currC = r, c\n totalSteps += steps \n return totalSteps\n \n # 2. use BFS get min distance for tree to tree\n def bfsGetMinSteps(self, forest, currR, currC, targetR, targetC):\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n m, n = len(forest), len(forest[0])\n q = collections.deque([(currR, currC)])\n visited = set([(currR, currC)])\n steps = 0\n \n while q:\n sameLevelCounts = len(q)\n for _ in range(sameLevelCounts):\n r, c = q.popleft()\n if r == targetR and c == targetC:\n return steps\n for dr, dc in directions:\n nextR, nextC = r + dr, c + dc\n if 0 <= nextR < m and 0 <= nextC < n and (nextR, nextC) not in visited and forest[nextR][nextC] != 0:\n visited.add((nextR, nextC))\n q.append((nextR, nextC))\n steps += 1\n return -1\n```
6
0
['Breadth-First Search', 'Heap (Priority Queue)', 'Python']
0
cut-off-trees-for-golf-event
[C++] || BFS FOR BEGINNERS || EASY
c-bfs-for-beginners-easy-by-decode_apoca-jc4u
WE CANNOT USE A SIMPLE RECURSION CONCEPT HERE, IT WILL TLE. It is because this question is asking us to now find trees in increasing order, but cut trees in in
Decode_Apocalypse
NORMAL
2022-09-03T05:26:49.896420+00:00
2022-12-20T07:45:35.777071+00:00
1,096
false
WE CANNOT USE A SIMPLE RECURSION CONCEPT HERE, IT WILL TLE. It is because this question is asking us to now find trees in increasing order, but cut trees in increasing order, so there will be cases when you will ignore the tree and will again return back to it. Kind of like a question where, minimum time to visit all nodes and return back to source question\n\nSEE THE BELOW MATRIX FOR EXAMPLE\n\n5 8 9\n25 19 10\n99 0 22\n\nOur start point will always be (0,0) but we wanna cut off the smallest tree first of all, so we try to find the walk count from 0,0 to the shortest tree height index, and then we make this tree index as our start index for the next greater tree height and continue on and on\n\n**If you are standing in a cell with a tree, you can choose whether to cut it off.**\nThe important condition is to cut the shortest tree first, and move on to next greater\n```\nclass Solution {\npublic:\n int BFS(vector<vector<int>> &forest, int sX, int sY, int dX, int dY){\n int n=forest.size();\n int m=forest[0].size();\n int X[4]={1,-1,0,0};\n int Y[4]={0,0,1,-1};\n vector<vector<bool>> vis(n,vector<bool>(m,false));\n queue<pair<int,int>> q;\n q.push({sX,sY});\n vis[sX][sY]=true;\n int res=0;\n while(!q.empty()){\n int size=q.size();\n while(size--){\n auto curr=q.front();\n q.pop();\n if(curr.first==dX && curr.second==dY){\n return res;\n }\n for(int dir=0;dir<4;dir++){\n int newX=curr.first+X[dir];\n int newY=curr.second+Y[dir];\n if(newX<0 || newY<0 || newX==n || newY==m || forest[newX][newY]==0 || vis[newX][newY]==true){\n continue;\n }\n vis[newX][newY]=true;\n q.push({newX,newY});\n }\n }\n res++;\n }\n return -1;\n }\n \n int cutOffTree(vector<vector<int>>& forest) {\n int n=forest.size();\n int m=forest[0].size();\n vector<vector<int>> trees;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(forest[i][j]>1){\n trees.push_back({forest[i][j],i,j});\n }\n }\n }\n sort(trees.begin(),trees.end());\n int res=0;\n int startX=0;\n int startY=0;\n for(auto tree: trees){\n int treeX=tree[1];\n int treeY=tree[2];\n int distance=BFS(forest,startX,startY,treeX,treeY);\n if(distance==-1){\n return -1;\n }\n res+=distance;\n startX=treeX;\n startY=treeY;\n }\n return res;\n }\n};\n```
5
0
['Breadth-First Search', 'C']
1
cut-off-trees-for-golf-event
C++ || Solution approach || Commented BFS Code || Beats 95% at time of submission
c-solution-approach-commented-bfs-code-b-hg4w
Solution Approach:\nSince it is given that we need to visit node in increasing order. A simple direct BFS cannot solve our problem, because we might need to vis
this_is_neo
NORMAL
2022-05-19T18:44:06.465904+00:00
2022-05-19T18:44:54.579493+00:00
935
false
**Solution Approach:**\nSince it is given that we need to visit node in increasing order. A simple direct BFS cannot solve our problem, because we might need to visit single cell multiple times. \nExample: in below input, we will first move to 2 (1->3->2)[2 steps] , then from 2 we will move to 3(2->3)[1 step], then to 4,5,6,7,8 with one step each. so ans will be 2 + 1 + 1 + 1 + 1 + 1 + 1 = 8\n```\n\t\t1 3 2 \n\t\t0 4 5\n\t\t8 7 6\n```\n\nActual idea to solve this problem is move from first point to second, determine the steps required using BFS, then move from second point to third, again use BFS to find number of steps and so on. In end add all the steps required, which will be our final answer.\n\n**Algo:**\n1. Figure out all the point present in grid that are greater than 1 and needs to be visited.(save in vector)\n2. sort the vector obtained above. We will move as per this vector values.\n3. Apply standard BFS to determine steps required to move from [0,0] (point A) to cell with value = vector[0] (point B).\n4. Now make point A = point B and point B = vector[1] and apply BFS again, to determine steps required.\n5. Follow step 4 till all the vector is parsed or if one of the point is not reachable.\n6. Add all the steps obtained in step 4 and return as answer, if all points are reachable, else return -1.\n\n```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& f) {\n \n /* Way to move in 4 direction */\n int dx[] = {1,0,-1,0};\n int dy[] = {0,1,0,-1};\n \n /* keeping a copy of original forest */\n vector<vector<int>> orig(f.begin(),f.end());\n \n vector<int> p;\n \n /* store all the values that are greater than 1 */\n for(int i = 0 ; i < f.size(); i++ )\n {\n for(int j = 0; j < f[0].size(); j++)\n {\n if(f[i][j] > 1 )\n {\n p.push_back(f[i][j]);\n }\n }\n }\n \n /*sort the element, we will visit each node one by one in this order */\n sort(p.begin(),p.end());\n \n int ans = 0;\n \n int x = 0; /* x coordinate */\n int y = 0; /* y coordinate */\n int ans1 = 0; /* steps required to move from point A to point B */\n int vis = 0; /* Indicate whether it is possible to reach some point or not */\n int flag = 0; /* variable to break out of two loop,as goto is not a right option */\n \n \n /* outer loop will run for all values that needs to be visited. */\n for(int i = 0 ; i < p.size(); i++)\n {\n vis = 0;\n int val = p[i];\n \n queue<pair<int,int>> q;\n q.push({x,y});\n \n /* our standard BFS implementation with just one tweak \n -> break out of loop when our val is found and move on to next value. \n */\n while(!q.empty())\n {\n \n if(val == orig[q.front().first][q.front().second])\n { \n x = q.front().first; /* setting up coordinate for next iteration */\n y = q.front().second;\n vis = 1; /* if val is found, vis is made one otherwise we can directly return -1 */\n break;\n }\n \n ans1++; /* increasing step count for bfs */\n flag = 0;\n int size = q.size();\n \n while(size--)\n {\n \n pair<int,int> temp = q.front();\n q.pop();\n x = temp.first;\n y = temp.second;\n \n for(int j = 0 ;j < 4; j++)\n {\n int newX = x + dx[j];\n int newY = y + dy[j];\n \n if(newX >= 0 && newX < f.size() && newY >= 0 && newY < f[0].size() &&\n f[newX][newY] >= 1)\n {\n if(val == orig[newX][newY])\n { \n vis = 1; /* if val is found, vis is made one otherwise we can directly return -1 */\n x = newX; /* setting up coordinate for next iteration */\n y = newY;\n flag = 1;\n break;\n }\n q.push({newX,newY});\n f[newX][newY] = 0;/*making it 0 so our bfs will converge quicky */\n }\n }\n if(flag)\n {\n break;\n }\n }\n if(flag)\n break;\n }\n \n ans = ans + ans1; /* adding to the final result */\n \n /* copying original value to variable for next iterations*/\n flag = 0;\n f = orig;\n ans1 = 0;\n \n if(vis == 0) /* there is no path to reach a given point , return -1*/\n return -1;\n \n }\n return ans;\n \n }\n};\n```
5
0
['Breadth-First Search', 'C', 'Sorting']
0
cut-off-trees-for-golf-event
C++ solution using a* search
c-solution-using-a-search-by-xt2357-ejkn
\nclass Solution {\n\tint find(vector<vector<int>> &forest, int cur, int tar) {\n\t\tint n = forest[0].size(), m = forest.size();\n\t\tint tr = tar/n, tc = tar%
xt2357
NORMAL
2019-04-11T05:41:01.780126+00:00
2019-04-11T05:41:01.780195+00:00
650
false
```\nclass Solution {\n\tint find(vector<vector<int>> &forest, int cur, int tar) {\n\t\tint n = forest[0].size(), m = forest.size();\n\t\tint tr = tar/n, tc = tar%n, curr = cur/n, curc = cur%n;\n\t\tauto cmp = [](const pair<int,int> &a, const pair<int,int> &b) {\n\t\t\treturn a.second > b.second;\n\t\t};\n\t\tpriority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> q{cmp};\n\t unordered_set<int> vis;\n\t q.push(make_pair(cur, abs(tr-curr)+abs(tc-curc)));\n\t while (!q.empty()) {\n\t \tauto f = q.top();\n\t \tq.pop();\n\t\t\tif (vis.count(f.first)) continue;\n\t\t\tvis.insert(f.first);\n\t \tif (f.first == tar) return f.second;\n\t \tint dirs[][2] = {{1,0},{-1,0},{0,1},{0,-1}};\n\t \tint r = f.first/n, c = f.first%n;\n\t \tfor (auto &dir : dirs) {\n\t \t\tint newr = r + dir[0], newc = c + dir[1];\n\t \t\tif (newr < 0 || newr >= m || newc < 0 || newc >= n || \n\t \t\t\tforest[newr][newc] == 0 || vis.count(newr*n+newc)) continue;\n\t \t\tq.push(make_pair(newr*n+newc, f.second-abs(r-tr)-abs(c-tc)+1+abs(newr-tr)+abs(newc-tc)));\n\t \t}\n\t }\n\t return -1;\n\t}\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n if (forest.size() == 0 || forest[0].size() == 0) return 0;\n int m = forest.size(), n = forest[0].size();\n vector<int> targets;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (forest[i][j] > 1) targets.push_back(i*n+j);\n }\n }\n sort(targets.begin(), targets.end(), [&forest,n](int a, int b) {\n return forest[a/n][a%n] < forest[b/n][b%n];\n });\n int ans = 0, cur = 0;\n for (auto tar : targets) {\n auto dis = find(forest, cur, tar);\n if (dis == -1) return -1;\n ans += dis;\n cur = tar;\n }\n return ans;\n }\n};\n```\nbfs is too slow to passing the test cases
5
0
[]
2
cut-off-trees-for-golf-event
Java BFS + PriorityQueue solution with comments
java-bfs-priorityqueue-solution-with-com-6yt6
\nclass Solution {\n int[][] dirs = {{0,1}, {0, -1}, {1, 0}, {-1, 0}};\n public int cutOffTree(List<List<Integer>> forest) {\n // Sort trees by hei
ztcztc1994
NORMAL
2019-01-04T04:15:20.647356+00:00
2019-01-04T04:15:20.647403+00:00
990
false
```\nclass Solution {\n int[][] dirs = {{0,1}, {0, -1}, {1, 0}, {-1, 0}};\n public int cutOffTree(List<List<Integer>> forest) {\n // Sort trees by height\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>( new Comparator<int[]>(){\n public int compare(int[] p1, int[] p2){\n return p1[2] - p2[2];\n }\n });\n\n // Add trees in the pq\n for (int r = 0; r < forest.size(); ++r) \n for (int c = 0; c < forest.get(0).size(); ++c) {\n int height = forest.get(r).get(c);\n if (height >0) pq.add(new int[]{r, c, height});\n }\n \n int last_i = 0, last_j = 0;\n int result = 0;\n \n // Visit shorter trees first\n while (!pq.isEmpty()){\n int[] new_step = pq.poll();\n int step = bfs(forest, last_i, last_j, new_step[0], new_step[1]);\n if (step == -1) return -1;\n result += step;\n last_i = new_step[0];\n last_j = new_step[1];\n }\n return result;\n \n }\n \n // Using BFS to record shortest dist between two trees\n private int bfs(List<List<Integer>> forest, int start_i, int start_j, int end_i, int end_j){\n \n Queue<int[]> queue = new LinkedList();\n int m = forest.size(), n = forest.get(0).size();\n boolean[][] visited = new boolean[m][n];\n \n queue.add(new int[]{start_i, start_j});\n int level = 0;\n while(!queue.isEmpty()){\n int size = queue.size();\n for (int i=0; i<size; i++){\n int[] curr = queue.poll();\n\t\t\t\t// Target is found. Return the level of BFS traversal as steps\n if (curr[0] == end_i && curr[1] == end_j)\n return level;\n for (int j=0; j<4; j++){\n int next_i = curr[0]+dirs[j][0];\n int next_j = curr[1]+dirs[j][1];\n if (inBounds(forest, next_i , next_j) && ! visited[next_i][next_j]){\n visited[next_i][next_j] = true;\n queue.offer(new int[]{ next_i, next_j});\n }\n }\n }\n level++;\n }\n return -1;\n }\n \n // Return false if out of forest or meet obstacles\n private boolean inBounds(List<List<Integer>> forest, int i, int j){\n return (i >=0 && i<=forest.size()-1 && j >=0 && j<=forest.get(0).size()-1 && forest.get(i).get(j) != 0);\n }\n \n}\n```
5
0
[]
0
cut-off-trees-for-golf-event
Python currently fastest implementation 610ms (same method as @wufangjie's, perf improved)
python-currently-fastest-implementation-7p3vg
Disclaimer: * This solution is inspired by @wufangjie's solution (as I summarized below) * My contribution is to improve the performance to 610ms (currently fas
royitaqi
NORMAL
2018-02-19T04:56:07.488502+00:00
2018-02-19T04:56:07.488502+00:00
1,171
false
Disclaimer: * This solution is inspired by @wufangjie's solution (as I summarized below) * My contribution is to improve the performance to 610ms (currently fastest among all python submissions, with the second fastest be around 700ms) Summary of the solution: 1. first floodfill to make sure all trees are reachable for each pair of trees (pairs defined in step 3) 2. sort distances between all trees, call routine 3 to calculate minimum distance between pairs of trees (with closest height) and return the sum. 3. calculate the minimum distance between a pair of trees as following: 3.1. bfs through only the paths which can achieve theoretical minimum distance (i.e. `cost`) between the two points 3.2. while doing the above bfs, keep a note of the seed nodes which can achieve `cost + 2` distance 3.3. if 3.1 failed, switch to the next level, which is to bfs from the seed nodes found in 2.2 with `cost += 2` 3.4. keep the above loop 3.1 ~ 3.3, until there are no more seed nodes for the next level This implementation appears to be faster than @wufangjie's and is currently the fastest (i.e. beats 100% of the python solutions as of 2/18/2018). I submitted it three times to confirm that it's the fastest, got: 644 ms, 608 ms, 612 ms, with the second fastest running time from other submissions to be 700ms. The first part of the implemention is similar to @wufangjie's, while the last part (i.e. shortest distance between tree pairs) differs in some details. Two major differences: * The judgement of whether a movement will cost additional 2 steps is unified without many `if` statements. * New neighbors are directly added into existing queues without creating temporary lists. Side note: * The usage of `list`s with `append()` and `pop()` for `queue` and `next_queue` are important (as also did in @wufangjie's implementation). Changing them to `deque`s with `append()` and `popleft()` will slow down the perf about three times. ``` class Solution: d = [(1, 0), (-1, 0), (0, 1), (0, -1)] def cutOffTree(self, forest): #print(forest) rows = len(forest) if rows == 0: return 0 cols = len(forest[0]) if cols == 0: return 0 forest.append([0] * cols) for row in forest: row.append(0) trees = {(r, c) for c in range(cols) for r in range(rows) if forest[r][c] > 1} visited = {(0, 0)} queue = [(0, 0)] while len(queue) != 0: r, c = queue.pop() for nr, nc in ((r + dr, c + dc) for dr, dc in self.d): if (nr, nc) not in visited and forest[nr][nc] > 0: visited.add((nr, nc)) queue.append((nr, nc)) if trees.difference(visited): return -1 trees = sorted(trees, key=lambda t: forest[t[0]][t[1]]) if trees[0] != (0, 0): trees.insert(0, (0, 0)) num_trees = len(trees) #print('TREES:', trees) total_steps = 0 for i in range(1, num_trees): pr, pc = p = trees[i - 1] qr, qc = q = trees[i] cost = abs(pr - qr) + abs(pc - qc) queue, next_queue = [], [] # Using list: 0.53s, 0.52s, 0.54s #queue, next_queue = deque(), deque() # Using deque: 1.45s, 1.50s, 1.46s queue.append(p) visited, pending_visited = {p}, set() while len(queue) + len(next_queue) != 0: if len(queue) == 0: queue = next_queue next_queue = deque() visited.update(pending_visited) pending_visited = set() cost += 2 (r, c) = queue.pop() # Using list #(r, c) = queue.popleft() # Using deque #print('POP', r, c, cost) safe_dr = qr - r safe_dr = safe_dr and safe_dr // abs(safe_dr) safe_dc = qc - c safe_dc = safe_dc and safe_dc // abs(safe_dc) for dr, dc in self.d: nbr = (r + dr, c + dc) if nbr not in visited and forest[nbr[0]][nbr[1]] > 0: #print('SAFE', (safe_dr, safe_dc), 'D', (dr, dc)) if (dr == safe_dr and dc != -safe_dc) or (dc == safe_dc and dr != -safe_dr): queue.append(nbr) visited.add(nbr) ncost = cost #print('PUSH', nbr) else: next_queue.append(nbr) pending_visited.add(nbr) ncost = cost + 2 #print('PUSH NEXT', nbr) if nbr == q: #print('COST:', p, q, ncost) total_steps += ncost queue = next_queue = list() break # print('MAP', cost) # for rr in range(rows): # for cc in range(cols): # if (rr, cc) == (r, c): # print('*', end='') # elif (rr, cc) in queue: # print('Q', end='') # elif (rr, cc) in visited: # print('+', end='') # elif (rr, cc) in next_queue: # print('N', end='') # else: # print(forest[rr][cc], end='') # print() return total_steps ```
5
0
[]
0
cut-off-trees-for-golf-event
C++ Getting Accepted and TLE with same code
c-getting-accepted-and-tle-with-same-cod-sfpc
This same sol is submitting TLE and was approved following a few submissions without any changes.\n I\'ve experienced this rather frequently.\n Has anyone encou
dynamo_518
NORMAL
2022-10-19T14:10:39.877417+00:00
2022-10-21T12:08:52.685639+00:00
1,234
false
* ***This same sol is submitting TLE and was approved following a few submissions without any changes.***\n* ***I\'ve experienced this rather frequently.***\n* ***Has anyone encountered this issue??***\n```\nclass Solution {\n vector<int> dx{0,0,1,-1},dy{-1,1,0,0};\n int n,m;\n int BFS(vector<vector<int>>& forest ,int sx,int sy,int ex, int ey){\n vector<vector<bool>> vis(n,vector<bool>(m,false));int c = 0;\n queue<pair<int,int>> q;\n q.push({sx,sy});\n vis[sx][sy] = true;\n \n while(!q.empty()){\n int qs = q.size();\n while(qs--){\n \n pair<int,int> p = q.front();q.pop();\n \n if(p.first == ex and p.second == ey) return c;\n for(int i = 0;i<4;i++){\n int newX=p.first + dx[i];\n int newY=p.second + dy[i];\n if(newX<0 || newY<0 || newX==n || newY==m || forest[newX][newY]==0 || vis[newX][newY]==true)continue;\n vis[newX][newY]=true;\n q.push({newX,newY});\n }\n }c++;\n }\n return -1;\n }\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int ans = 0;n=forest.size(),m=forest[0].size();\n vector<vector<int>> v;\n for(int i = 0;i<n;i++){\n for(int j=0;j<m;j++){\n if(forest[i][j]>1) v.push_back({forest[i][j],i,j});\n }\n }\n sort(v.begin(),v.end());\n \n int sx = 0,sy=0;\n for(auto it:v){\n int minStepsForNextTree = BFS(forest,sx,sy,it[1],it[2]);\n if(minStepsForNextTree==-1) return -1;\n ans+=minStepsForNextTree;\n sx = it[1],sy=it[2];\n }\n return ans;\n }\n};\n```
4
0
['Breadth-First Search', 'C', 'Sorting']
1
cut-off-trees-for-golf-event
Java - ArrayList+BFS | NO TLE [with clear explanation and comments]
java-arraylistbfs-no-tle-with-clear-expl-mlpa
Complexities\n- Time Complexity: O(N^2 * M^2)\n- Space Complexity: O (N * M)\n\nThinking Process\n1. All trees shall be cut in the order of height -> we shall c
shanezzz
NORMAL
2022-03-10T03:25:34.440811+00:00
2022-03-14T05:55:45.155272+00:00
950
false
**Complexities**\n- Time Complexity: O(N^2 * M^2)\n- Space Complexity: O (N * M)\n\n**Thinking Process**\n1. All trees shall be cut in the order of height -> we shall create a list to store all of their heights and sort the list after all trees have been found\n2. Find the total steps need to cut all trees \n\t- Traverse through all tree -> traverse the list from index 0 (the tree with the smallest height)\n\t- Move to the next tree to cut -> use BFS to find the shortest path from current location to it\n\t(If a tree is unreacheable, then return -1)\n\n\n**PS**: \n1. *Why use ArrayList instead of PriorityQueue*? \n\tWe only need the **final** list to be sorted. If we were using PQ, then every insertion/deletion would need O(logK) time (K == size of PQ), making the process of adding all trees with a time complexity O(K log K) and polling all trees from the PQ with O(K log K). In comparison, ArrayList would only need to be sorted after all trees have been added, which having a time complexity of O(K log K) [< O(2K logK) if using PQ].\n\n\nPlease let me know if there\'s any mistakes. Thanks in advance.\n\n```\nclass Solution {\n static int[] dy = {-1, 0, 1, 0};\n static int[] dx = {0, 1, 0, -1};\n \n public int cutOffTree(List<List<Integer>> forest) {\n int n = forest.size(), m = forest.get(0).size();\n int count = 0;\n \n\t\t// Store the height of all trees in a list\n List<Integer> minList = new ArrayList<>();\n for (List<Integer> al: forest)\n for (int val: al) \n if (val > 1) \n minList.add(val);\n \n\t\t// Sort the list to have the smallest in the front\n Collections.sort(minList);\n\t\t\n int totalSteps = 0;\n int si = 0, sj = 0; // Starting points <i, j>\n \n for (int i = 0; i < minList.size(); i++) {\n int target = minList.get(i);\n boolean hasFound = false;\n boolean[][] visited = new boolean[n][m];\n\t\t\t\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{si, sj});\n \n int steps = -1;\n while (!q.isEmpty() && !hasFound) {\n steps++; // Increment the steps for current move\n\t\t\t\t\n\t\t\t\t// Level-Order Traversal\n\t\t\t\tint size = q.size();\n while (size -- > 0) {\n int[] curr = q.poll();\n\t\t\t\t\t\n if (visited[curr[0]][curr[1]]) continue;\n visited[curr[0]][curr[1]] = true;\n \n\t\t\t\t\t// Skip if 0 is encountered\n if (forest.get(curr[0]).get(curr[1]) == 0) continue;\n \n\t\t\t\t\tif (forest.get(curr[0]).get(curr[1]) == target) {\n si = curr[0];\n sj = curr[1];\n hasFound = true;\n break;\n }\n\n\t\t\t\t\t// Typical BFS process\n for (int j = 0; j < dy.length; j++) {\n int y = curr[0] + dy[j];\n int x = curr[1] + dx[j];\n\t\t\t\t\t\t\n if (y >= n || x >= m || y < 0 || x < 0 || visited[y][x] || forest.get(y).get(x) == 0) \n continue;\n q.offer(new int[]{y, x});\n }\n }\n }\n\t\t\t// If the target is unreacheable, end the entire process\n if (steps == -1 || !hasFound) return -1;\n\n\t\t\ttotalSteps += steps;\n }\n return totalSteps;\n }\n}\n```
4
0
['Breadth-First Search', 'Java']
1
cut-off-trees-for-golf-event
Python, normal and priority BFS, faster than 99% and faster than 77%
python-normal-and-priority-bfs-faster-th-wdtb
normal bfs\n\n\n\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n forest.append([0] * len(forest[0]))\n for row in fo
dustlihy
NORMAL
2021-05-12T06:23:59.195082+00:00
2021-05-12T06:24:10.880264+00:00
1,258
false
## normal bfs\n![image](https://assets.leetcode.com/users/images/f70bca63-7c1d-4a5d-9b9b-d2a5ac4733e7_1620800536.5729027.png)\n\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n forest.append([0] * len(forest[0]))\n for row in forest: row.append(0)\n def bfs(end, start):\n if end == start: return 0\n visited, queue = set(), {start}\n visited.add(start)\n step = 0\n while queue:\n s = set()\n step += 1\n for p in queue: \n for dr, dc in ((-1, 0), (1, 0), (0, 1), (0, -1)):\n r, c = p[0] + dr, p[1] + dc\n if not forest[r][c] or (r, c) in visited: continue\n if (r, c) == end: return step\n visited.add((r, c))\n s.add((r, c))\n queue = s\n\n trees = [(height, r, c) for r, row in enumerate(forest) for c, height in enumerate(row) if forest[r][c] > 1]\n # check\n queue = [(0, 0)]\n reached = set()\n reached.add((0, 0))\n while queue:\n r, c = queue.pop()\n for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n row, col = r + dr, c + dc\n if forest[row][col] and (row, col) not in reached:\n queue.append((row, col))\n reached.add((row,col))\n if not all([(i, j) in reached for (height, i, j) in trees]): return -1\n trees.sort()\n return sum([bfs((I,J),(i,j)) for (_, i, j), (_, I, J) in zip([(0, 0, 0)] + trees, trees)])\n```\n## priority bfs\n![image](https://assets.leetcode.com/users/images/87009e0b-3b8f-4ad1-96db-f3582810ef95_1620800616.6076303.png)\n\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n forest.append([0] * len(forest[0]))\n for row in forest: row.append(0)\n # distance\n def distance(i, j, I, J):\n manhattan = abs(i - I) + abs(j - J)\n detour = 0\n good, bad = [(i, j)], []\n visited = set()\n while True:\n if not good:\n good, bad = bad, []\n detour += 1\n i, j = good.pop()\n if i == I and j == J: return manhattan + detour * 2\n if (i, j) in visited: continue\n visited.add((i, j))\n for i, j, closer in ((i-1, j, i > I), (i+1, j, i < I), (i, j+1, j < J), (i, j-1, j > J)):\n if forest[i][j]:\n (good if closer else bad).append((i, j))\n \n trees = [(height, r, c) for r, row in enumerate(forest) for c, height in enumerate(row) if forest[r][c] > 1]\n # check\n queue = [(0, 0)]\n reached = set()\n reached.add((0, 0))\n while queue:\n r, c = queue.pop()\n for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n row, col = r + dr, c + dc\n if forest[row][col] and (row, col) not in reached:\n queue.append((row, col))\n reached.add((row,col))\n if not all([(i, j) in reached for (height, i, j) in trees]): return -1\n trees.sort()\n return sum([distance(i, j, I, J) for (_, i, j), (_, I, J) in zip([(0, 0, 0)] + trees, trees)])\n```
4
0
['Breadth-First Search', 'Python', 'Python3']
0
cut-off-trees-for-golf-event
Java Simple BFS Solution
java-simple-bfs-solution-by-jianhuilin11-qcfa
\nclass Solution {\n int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n int rows;\n int cols;\n public int cutOffTree(List<List<Integer>> forest)
jianhuilin1124
NORMAL
2020-09-15T00:24:11.288114+00:00
2020-09-15T00:24:11.288153+00:00
717
false
```\nclass Solution {\n int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n int rows;\n int cols;\n public int cutOffTree(List<List<Integer>> forest) {\n rows = forest.size();\n cols = forest.get(0).size();\n int[][] matrix = new int[rows][cols];\n TreeMap<Integer, int[]> map = new TreeMap<>();\n for (int r = 0; r < rows; ++r) {\n for (int c = 0; c < cols; ++c) {\n matrix[r][c] = forest.get(r).get(c);\n if (matrix[r][c] > 1) {\n map.put(matrix[r][c], new int[]{r, c});\n }\n }\n }\n int x = 0, y = 0, res = 0;\n for (int t : map.keySet()) {\n int[] pos = map.get(t);\n boolean[][] visited = new boolean[rows][cols];\n int step = bfs(x, y, pos[0], pos[1], matrix, visited);\n if (step == -1) {\n return -1;\n }\n res += step;\n matrix[x][y] = 1;\n x = pos[0];\n y = pos[1];\n }\n return res;\n }\n \n private int bfs(int r, int c, int x, int y, int[][] matrix, boolean[][] visited) {\n Queue<int[]> queue = new ArrayDeque<>();\n queue.offer(new int[]{r, c});\n visited[r][c] = true;\n int step = 0;\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; ++i) {\n int[] cur = queue.poll();\n if (cur[0] == x && cur[1] == y) {\n return step;\n }\n for (int[] dir : dirs) {\n int nr = dir[0] + cur[0];\n int nc = dir[1] + cur[1];\n if (0 <= nr && nr < rows && 0 <= nc && nc < cols && matrix[nr][nc] > 0 && !visited[nr][nc]) {\n visited[nr][nc] = true;\n queue.offer(new int[]{nr, nc});\n }\n }\n }\n step++;\n }\n return -1;\n }\n}\n```
4
0
['Java']
0
cut-off-trees-for-golf-event
C++ solution avoid TLE in 2019
c-solution-avoid-tle-in-2019-by-yc0-lv2h
The idea is that find the heights of trees in order as your multiple goals. Then, you go traverse the tree one by one from your goals.\nOriginally, you can easi
yc0
NORMAL
2019-09-12T03:48:56.887496+00:00
2019-09-12T05:19:57.202552+00:00
340
false
The idea is that find the heights of trees in order as your multiple goals. Then, you go traverse the tree one by one from your goals.\nOriginally, you can easily pass by the solution like above method. However, new testcases impose extra computing time so that you might encouter TLE issue.\n\nHere is what I modify.\n1) adopt ```pair<int,int>``` instead of ```vector<int>```;\n2) avoid copying by value operations; this is also common sense.\n3) try allocate your memory by essential operations, such as int x[][] instead;\n\nthe time complexity is O((m*n)\xB2); then, space complexity is O(m*n).\n\nThe following is my implementation. At first section, I fill out my goals, and sort the goals. For that, you can implement it by priority_queue as well. But it might incur extra computing resources like push, pop. Afterwards, at second section, I bfs my shortest path from source to target spots. After the initated source goal you reach, you pick up the subsequent goal from your candidate goals as your new target, and alter original target into you new source spot. If you cannot get your target for the round, directly return -1; otherwise, you can keep going and accumulating your step.\n\n```\nclass Solution {\n const int xs[4] = {0, 0,-1,1};\n const int ys[4] = {-1,1, 0,0};\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n std::ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n if (forest.empty() || forest[0].empty()) return -1;\n int m = forest.size(),\n n = forest[0].size();\n\n vector<vector<int>> goal;\n\n for(int r=0; r < m; r++) {\n for(int c=0; c < n; c++) {\n if(forest[r][c] > 1) {\n goal.push_back({r,c});\n }\n }\n }\n\n sort(begin(goal), end(goal), [&forest](const vector<int>& a, const vector<int> &b) {\n return forest[a[0]][a[1]] < forest[b[0]][b[1]];\n });\n\n\n\n vector<int> start = {0,0};\n int rst = 0;\n for(auto &g : goal) {\n auto cur = bfs(m,n, start, g, forest);\n if( cur == -1) return -1;\n rst += cur;\n start = g;\n }\n return rst;\n }\n\n int bfs(const int &m, const int& n, vector<int>& src, vector<int>& target, vector<vector<int>>& forest)\n {\n bool visited[m][n];\n memset(visited, 0, sizeof(visited));\n\n queue<pair<int,int>> q;\n q.push({src[0],src[1]});\n visited[src[0]][src[1]] = true;\n register int step = 0;\n while(!q.empty()) {\n int sz = q.size();\n for(int i=0; i < sz; ++i) {\n auto from = q.front(); q.pop();\n if(from.first == target[0] && from.second==target[1]) return step; // to handle the first spot like example 3\n for(int d = 0; d < 4; ++d) {\n auto R = from.first+xs[d],\n C = from.second+ys[d];\n if(0<= R && R < m && 0 <= C && C < n && !visited[R][C] && forest[R][C] >= 1) {\n visited[R][C] = true;\n q.push({R,C});\n if(R == target[0] && C == target[1]) return step+1;\n }\n }\n }\n ++step;\n }\n return -1;\n\n }\n};\n```
4
0
[]
1
cut-off-trees-for-golf-event
readable python solution using Heap and BFS
readable-python-solution-using-heap-and-k7yqn
\ndef cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: int\n """\n m, n = len(forest), len(forest[0]
bryantbyr
NORMAL
2019-01-16T13:19:55.179772+00:00
2019-01-16T13:19:55.179837+00:00
850
false
```\ndef cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: int\n """\n m, n = len(forest), len(forest[0])\n heap = [(forest[i][j], i, j) for i in range(m) for j in range(n) if forest[i][j] > 1]\n heapq.heapify(heap)\n\n def get_distance(x1, y1, x2, y2):\n if x1 == x2 and y1 == y2:\n return 0\n queue, dist, visited = [(x1, y1)], 0, {(x1, y1)}\n while queue:\n new_queue = []\n dist += 1\n for r, c in queue:\n for dir in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n nr, nc = r + dir[0], c + dir[1]\n if 0 <= nr < m and 0 <= nc < n and (nr, nc) not in visited and forest[nr][nc] != 0:\n visited.add((nr, nc))\n if nr == x2 and nc == y2:\n return dist\n new_queue.append((nr, nc))\n queue = new_queue\n return -1\n\n res = 0\n x, y = 0, 0\n while heap:\n _, nx, ny = heapq.heappop(heap)\n dist = get_distance(x, y, nx, ny)\n if dist == -1:\n return -1\n res += dist\n x, y = nx, ny\n\n return res\n```
4
0
[]
1
cut-off-trees-for-golf-event
c++ priority queue + bfs solution with comments
c-priority-queue-bfs-solution-with-comme-28dg
\n\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int rows = forest.size();\n int cols = rows ? forest[0].size()
anilnagori
NORMAL
2019-01-12T23:45:07.650686+00:00
2019-01-12T23:45:07.650732+00:00
862
false
```\n\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int rows = forest.size();\n int cols = rows ? forest[0].size() : 0;\n \n if (!rows || !cols) {\n return 0;\n }\n \n // Start location is blocked\n if (forest[0][0] == 0) {\n return -1;\n }\n \n // Min queue of trees based on height\n priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> trees;\n \n for (int r = 0; r < rows; ++r) {\n for (int c = 0; c < cols; ++c) {\n if (forest[r][c] > 1) {\n trees.push({forest[r][c], {r, c}}); \n }\n }\n }\n \n // Legal moves\n vector<pair<int, int>> moves = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n \n // Track visited\n vector<vector<int>> visited(rows, vector<int>(cols, -1));\n \n // Total distance\n int totalDist = 0;\n \n // Start location\n pair<int, int> start = {0, 0};\n \n // Tree ID\n int i = 0;\n \n // Iterate through trees in increasing height order\n while (!trees.empty()) {\n pair<int, int> to = trees.top().second;\n trees.pop();\n \n // Level order traversal\n bool found = false;\n int dist = -1; \n queue<pair<int, int>> qu;\n \n qu.push({start.first, start.second});\n visited[start.first][start.second] = i;\n \n while (!qu.empty() && !found) {\n ++dist;\n \n for (int j = 0, r, c, size = qu.size(); j < size && !found; ++j) {\n tie(r, c) = qu.front();\n qu.pop();\n \n // Break if target location found\n if (r == to.first && c == to.second) {\n found = true;\n break;\n }\n \n for (int m = 0, nr, nc; m < 4; ++m) {\n // New location\n nr = r + moves[m].first;\n nc = c + moves[m].second;\n\n // Skip out of bound, blockages and already scheduled\n if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || visited[nr][nc] == i || forest[nr][nc] == 0) {\n continue;\n }\n \n // Mark visited asap otherwise it will be scheduled mutiple times\n visited[nr][nc] = i;\n qu.push({nr, nc});\n }\n }\n }\n \n // Return if not found\n if (!found) {\n return -1;\n }\n \n // Update total distance\n totalDist += dist;\n \n // Update start\n start = to;\n \n // Update id\n ++i;\n }\n \n return totalDist;\n }\n};\n\n```
4
0
[]
1
cut-off-trees-for-golf-event
C++ Sorting + BFS Solution
c-sorting-bfs-solution-by-hb05-5lk1
cpp\ntypedef vector<vector<int>> vvi; \ntypedef vector<vector<bool>> vvb; \nclass Solution {\npublic:\n bool isValid(int x, int y, int n, int m){\n re
hb05
NORMAL
2022-06-24T08:08:25.802784+00:00
2022-06-24T08:08:25.802811+00:00
760
false
```cpp\ntypedef vector<vector<int>> vvi; \ntypedef vector<vector<bool>> vvb; \nclass Solution {\npublic:\n bool isValid(int x, int y, int n, int m){\n return x>=0 && y>=0 && x<n && y<m; \n }\n // The function gives the length of shortest path\n // from (x1,y1)->(x2,y2)\n int bfs(int x1, int y1, int x2,int y2, vvi &forest){\n int n = forest.size(), m = forest[0].size(); \n int dx[4] = {1,-1,0,0};\n int dy[4] = {0,0,1,-1}; \n vector<vector<bool>> vis(n, vector<bool>(m, false)); \n queue<pair<int, int>> q;\n q.push({x1, y1}); \n vis[x1][y1] = true;\n int cnt = 0; \n // Level Order Traversal\n while(!q.empty()){\n int sz = q.size(); \n while(sz--){\n auto node = q.front(); q.pop(); \n int x = node.first, y = node.second; \n if(x == x2 && y==y2)\n return cnt; \n for(int i = 0; i<4; ++i){\n int xr = x + dx[i], yr = y + dy[i]; \n if(isValid(xr,yr,n,m) && !vis[xr][yr]){\n if(forest[xr][yr] > 0){\n q.push({xr,yr});\n vis[xr][yr] = true; \n }\n }\n }\n }\n cnt++; \n }\n return -1; \n }\n int cutOffTree(vector<vector<int>>& forest) {\n if(forest[0][0] == 0)\n return -1; \n int n = forest.size(), m = forest[0].size(); \n // Collect the trees with coordinates in heightwise order\n vector<pair<int, pair<int, int>>> trees; \n for(int i = 0; i<n; ++i){\n for(int j = 0; j<m; ++j){\n if(forest[i][j] > 1){\n trees.push_back({forest[i][j], {i,j}}); \n }\n }\n }\n sort(trees.begin(), trees.end()); \n if(trees[0].second.first != 0 || trees[0].second.second != 0)\n trees.insert(trees.begin(), {0,{0,0}});\n // Traverse the order and find the shortest path between two adj trees\n int steps = 0; \n for(int i = 1; i<trees.size(); ++i){\n auto src = trees[i-1].second; \n auto dest = trees[i].second; \n int x1 = src.first, y1 = src.second; \n int x2 = dest.first, y2 = dest.second; \n int cnt = bfs(x1, y1, x2, y2, forest); \n if(cnt == -1)\n return -1; \n steps += cnt; \n }\n return steps; \n }\n};\n```
3
0
['Breadth-First Search', 'Graph', 'C', 'Sorting', 'C++']
1
cut-off-trees-for-golf-event
Nightmare for Python coders
nightmare-for-python-coders-by-huikingla-vpbx
I bothered to try different Python algorithms on the forum. Only the one which used A passes reliably. I also tried to optimize my BFS code, comparing heap vs s
huikinglam02
NORMAL
2022-06-15T04:14:00.587344+00:00
2022-06-15T04:15:14.857147+00:00
507
false
I bothered to try different Python algorithms on the forum. Only the one which used A* passes reliably. I also tried to optimize my BFS code, comparing heap vs sort, and using set vs array to store visited (array seems to be a little faster). None of them yield a big difference.\n\nI found that a monstrous testcase (54) causes similar amount of time between A* and BFS, but A* is consistently faster than BFS in earlier testcases.
3
0
[]
0
cut-off-trees-for-golf-event
Java A* 91% Speed&Mem with Explanations.
java-a-91-speedmem-with-explanations-by-fb3f2
If you are not familiar with A search, read this https://www.redblobgames.com/pathfinding/a-star/introduction.html first. It comes in handy with quesitons like
Student2091
NORMAL
2021-12-01T06:43:37.917689+00:00
2021-12-01T06:48:05.514285+00:00
372
false
If you are not familiar with A* search, read this https://www.redblobgames.com/pathfinding/a-star/introduction.html first. It comes in handy with quesitons like this. This question basically boils down to how to effectively search for the next tree to cut down when they are all over the map. A* is great for this while standard BFS may give TLE. A* uses a priorityQueue to achieve its effectiveness.\n\nLet\'s take down the problem into several parts:\n\nPart 1: Count how many trees there are and record their positon and heights with a List.\nPart 2: Check if we can reach all the trees, if not, return -1 here.\nPart 3: Sort the ArrayList in accordance with their height.\nPart 4: Start our A* search and loop it until there is no more tree to cut\nPart 5: Return the result. \n\nThe below is my code for reference\n```\nclass Solution {\n private static int N;\n private static int M;\n private static final int[][] dirs = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};\n\n public int cutOffTree(List<List<Integer>> forest) {\n N = forest.size();\n M = forest.get(0).size();\n \n List<int[]> trees = new ArrayList<>();\n for (int i = 0; i < N; i++)\n for (int j = 0; j < M; j++)\n if (forest.get(i).get(j) > 1)\n trees.add(new int[]{i, j, forest.get(i).get(j)});\n\n if (trees.size() != reachableTrees(forest, 0, 0, new boolean[N][M])) return -1;\n Collections.sort(trees, Comparator.comparingInt(o -> o[2]));\n\n int ans = 0;\n int idx = 0;\n int pr = 0;\n int pc = 0;\n while(idx < trees.size()){\n int tr = trees.get(idx)[0];\n int tc = trees.get(idx++)[1];\n PriorityQueue<int[]> minheap = new PriorityQueue<>(Comparator.comparingInt(o -> o[0]));\n minheap.offer(new int[]{dist(pr, pc, tr, tc), 0, pr, pc}); // priority, steps, r, c\n boolean[][] seen = new boolean[N][M];\n while(!minheap.isEmpty()){\n int[] cur = minheap.poll();\n int pri = cur[0];\n int steps = cur[1];\n int r = cur[2];\n int c = cur[3];\n if (r == tr && c == tc) {ans += steps; break;}\n seen[r][c] = true;\n\n for (int[] d : dirs){\n int nr = r + d[0];\n int nc = c + d[1];\n if (nr < 0 || nc < 0 || nr >= N || nc >= M || seen[nr][nc]\n || forest.get(nr).get(nc) == 0)\n continue;\n minheap.offer(new int[]{dist(nr, nc, tr, tc) + steps + 1, steps + 1, nr, nc});\n }\n }\n pr = tr;\n pc = tc;\n }\n return ans;\n }\n\n private int reachableTrees(List<List<Integer>> forest, int r, int c, boolean[][] seen){\n if (r < 0 || r >= N || c < 0 || c >= M || seen[r][c]\n || forest.get(r).get(c) == 0) return 0;\n\n seen[r][c] = true;\n\n return (forest.get(r).get(c) > 1? 1 : 0) \n + reachableTrees(forest, r + 1, c, seen)\n + reachableTrees(forest, r - 1, c, seen)\n + reachableTrees(forest, r, c + 1, seen)\n + reachableTrees(forest, r, c - 1, seen);\n }\n\n private int dist(int x, int y, int dx, int dy){\n return Math.abs(x - dx) + Math.abs(y - dy);\n }\n}\n```
3
1
['Breadth-First Search', 'Heap (Priority Queue)', 'Java']
1
cut-off-trees-for-golf-event
Python bidirectional BFS accepted
python-bidirectional-bfs-accepted-by-use-107n
Python seems to be too slow unless BFS is bothways. \n\n\nclass Solution:\n def processQueue(self, queue, selfVisited, targetVisited):\n for _ in range(len(
user3399
NORMAL
2021-06-30T05:44:50.668245+00:00
2021-06-30T05:44:50.668303+00:00
254
false
Python seems to be too slow unless BFS is bothways. \n\n```\nclass Solution:\n def processQueue(self, queue, selfVisited, targetVisited):\n for _ in range(len(queue)):\n cr, cc = queue.popleft()\n if (cr, cc) in targetVisited:\n return True\n\n for d in self.dir:\n nr, nc = cr + d[0], cc + d[1]\n if nr >= self.R or nc >= self.C or nr < 0 or nc < 0:\n continue\n if self.fr[nr][nc] == 0:\n continue\n if (nr, nc) in selfVisited:\n continue\n queue.append((nr, nc))\n selfVisited.add((nr,nc))\n \n return False\n \n def findNext(self, pos, target):\n beginque= deque()\n endque= deque()\n beginque.append(pos)\n endque.append(target)\n step = 0\n visitedFromBegin = set()\n visitedFromBegin.add(pos)\n visitedFromEnd = set()\n visitedFromEnd.add(target)\n\n while beginque or endque:\n if self.processQueue(beginque, visitedFromBegin, visitedFromEnd):\n return step\n step += 1\n \n if self.processQueue(endque, visitedFromEnd, visitedFromBegin):\n return step\n step += 1\n \n return -1\n\n\n def cutOffTree(self, forest: List[List[int]]) -> int:\n self.dir = [(0,1), (1,0), (0,-1), (-1,0)]\n self.fr = forest\n self.R = len(forest)\n self.C = len(forest[0])\n\n trees = []\n treePos = dict()\n for r in range(self.R):\n for c in range(self.C):\n if self.fr[r][c] > 0:\n trees.append(self.fr[r][c])\n treePos[self.fr[r][c]] = (r,c)\n\n trees.sort(reverse=True)\n\n ret = 0\n pos = (0,0)\n while trees:\n nextTree = trees.pop()\n if nextTree == 1:\n continue\n steps = self.findNext(pos, treePos[nextTree])\n if steps == -1:\n return -1\n ret += steps\n pos = treePos[nextTree]\n\n return ret\n```
3
0
[]
1
cut-off-trees-for-golf-event
Java solution explained
java-solution-explained-by-bonam-cg1b
Before moving into the solution there are a couple of questions to be asked during the interview.\n What if the first cell is 0?\n Can there be a tree in the st
bonam
NORMAL
2021-06-19T00:25:21.837193+00:00
2021-06-20T22:19:26.653069+00:00
364
false
Before moving into the solution there are a couple of questions to be asked during the interview.\n* What if the first cell is 0?\n* Can there be a tree in the start location (0, 0)?\n* Can we walk though the trees?\n* What is the behaviour if there are trees with same height? Is there any preference order to be considered?\n\nKeeping the above points in mind, we can arrive at the below algorithm.\n* Define a class which stores the cell information containing x, y location and the tree height.\n* We need trees sorted in non-decreasing order while travelling through the forest. A min heap (priority queue) is a good choice for the same.\n* While adding cell information to the min heap, make sure only the trees are added and not the cells containing 0 or 1.\n* We need to find out the minimum distance to be travelled from the given source and the destination. We can pick BFS to find it.\n\nWhen do I know if there is no possible path to cut all the trees in the forest?\n* If the start location contains a 0 value.\n* If there is no path for the given source and destination, i.e no path between tree1 and tree2 with increasing heights.\n\n```\nclass Solution {\n class Cell implements Comparable<Cell> {\n int x;\n int y;\n int tree;\n public Cell(int x, int y, int tree) {\n this.x = x;\n this.y = y;\n this.tree = tree;\n }\n public int compareTo(Cell cell) {\n return this.tree <= cell.tree ? -1 : 1;\n }\n public boolean equals(Cell cell) {\n return this.x == cell.x && this.y == cell.y;\n }\n }\n \n int N, M;\n public int cutOffTree(List<List<Integer>> forest) {\n PriorityQueue<Cell> pq = new PriorityQueue<>();\n N = forest.size();\n M = forest.get(0).size();\n for(int i=0; i<N; i++) {\n for(int j=0; j<M; j++) {\n if(forest.get(i).get(j) > 1)\n pq.add(new Cell(i, j, forest.get(i).get(j)));\n }\n }\n \n int minPath = 0;\n if(forest.get(0).get(0) == 0) {\n return -1;\n }\n \n Cell source = new Cell(0,0,forest.get(0).get(0));\n while(!pq.isEmpty()) {\n Cell dest = pq.remove();\n int path = getMinPath(forest, source, dest);\n if(path == -1)\n return -1;\n\n minPath += path;\n source = dest;\n }\n \n return minPath;\n }\n \n int[][] dir = new int[][]{{1,0}, {0,1}, {-1,0}, {0,-1}};\n private int getMinPath(List<List<Integer>> forest, Cell source, Cell dest) {\n Deque<Cell> queue = new ArrayDeque<>();\n boolean[][] isVisited = new boolean[N][M];\n queue.add(source);\n int path = 0;\n while(!queue.isEmpty()) {\n int size = queue.size();\n while(size-- > 0) {\n Cell cell = queue.remove();\n if(cell.equals(dest)) {\n return path;\n }\n \n for(int k=0; k<4; k++) {\n int x = cell.x + dir[k][0];\n int y = cell.y + dir[k][1];\n if(checkBoundary(x, y, N, M) && !isVisited[x][y] && forest.get(x).get(y) != 0) {\n queue.add(new Cell(x, y, forest.get(x).get(y)));\n isVisited[x][y] = true;\n }\n }\n }\n path++;\n }\n \n return -1;\n }\n \n private boolean checkBoundary(int x, int y, int N, int M) {\n return x>=0 && y>=0 && x<N && y<M;\n }\n}\n```\n
3
0
[]
2
cut-off-trees-for-golf-event
Simple BFS + priority queue solution beats 90%
simple-bfs-priority-queue-solution-beats-lxn7
Approach -> Apply BFS from src node (initially (0,0)) to the smallest node with value >1. If there is no path then return -1. Else continue the iteration until
puff_diddy
NORMAL
2020-09-11T05:55:02.922377+00:00
2020-09-11T05:55:02.922419+00:00
251
false
Approach -> Apply BFS from src node (initially (0,0)) to the smallest node with value >1. If there is no path then return -1. Else continue the iteration until you have cut all the trees in ascending order or you can\'t find a path anymore.\n\nclass Solution {\npublic:\n bool is_valid(int x,int y,int n,int m,vector<vector<int>> &mat)\n {\n if(x<0 || x>=n || y<0 || y>=m || mat[x][y]==0)\n return false;\n \n return true;\n }\n int cutOffTree(vector<vector<int>>& mat) {\n \n int n=mat.size();\n int m=mat[0].size();\n if(n==0)\n return 0;\n \n if(mat[0][0]==0)\n return -1;\n int curr_x=0,curr_y=0;\n int ans=0;\n priority_queue<pair<int,pair<int,int>>> pq;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(mat[i][j]>1)\n pq.push({-mat[i][j],{i,j}});\n }\n }\n bool vis[n][m];\n while(!pq.empty())\n {\n pair<int,pair<int,int>> t=pq.top();\n pq.pop();\n int final_x=t.second.first;\n int final_y=t.second.second;\n queue<pair<int,int>> q;\n q.push({curr_x,curr_y});\n memset(vis,false,sizeof vis);\n vis[curr_x][curr_y]=true;\n int lvl=0;\n int arr[]={1,0,-1,0};\n int brr[]={0,1,0,-1};\n bool ok=false;\n while(!q.empty())\n {\n int si=q.size();\n for(int i=0;i<si;i++)\n {\n pair<int,int> s=q.front();\n q.pop();\n if(s.first==final_x && s.second==final_y)\n {\n ans+=lvl;\n ok=true;\n break;\n }\n for(int i=0;i<4;i++)\n {\n int x=s.first+arr[i];\n int y=s.second+brr[i];\n if(is_valid(x,y,n,m,mat))\n {\n if(vis[x][y]==false)\n {\n vis[x][y]=true;\n q.push({x,y});\n }\n }\n }\n }\n if(ok)\n break;\n \n lvl++;\n }\n if(ok==false)\n return -1;\n \n curr_x=final_x;\n curr_y=final_y;\n \n }\n \n return ans;\n }\n};
3
0
[]
1
cut-off-trees-for-golf-event
Simple Python BFS, No TLE
simple-python-bfs-no-tle-by-randomsixer-imnq
I modified the solution to pass in length or rows and columns and did visited True before adding to queue, that got rid of TLE.\nRuntime: 6252 ms\tMemory: 14.2
randomsixer
NORMAL
2020-04-02T03:25:01.211092+00:00
2020-04-11T18:49:33.712242+00:00
735
false
I modified the solution to pass in length or rows and columns and did visited True before adding to queue, that got rid of TLE.\nRuntime: 6252 ms\tMemory: 14.2 MB Rank: 58%\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n \n m, n = len(forest), len(forest[0])\n trees = []\n \n for r in range(m):\n for c in range(n):\n v = forest[r][c]\n if v > 1:\n trees.append((v, r, c)) \n \n trees.sort()\n \n sr, sc = 0, 0\n total_cost = 0\n for tree in trees:\n height, tr, tc = tree\n d = self.bfs(forest, sr, sc, tr, tc, m, n)\n if d < 0: return -1\n total_cost += d\n sr, sc = tr, tc\n \n return total_cost\n \n def bfs(self, forest, sx, sy, tx, ty, m, n):\n \n queue = collections.deque([(sx, sy, 0)])\n visited = [[False]*n for _ in range(m)]\n visited[sx][sy] = True\n \n while queue:\n sr, sc, d = queue.popleft()\n if sr == tx and sc == ty: return d\n for x, y in [[1, 0], [0, 1], [-1, 0], [0, -1]]:\n nr, nc = sr+x, sc+y\n if 0 <= nr < m and 0 <= nc < n and not visited[nr][nc] and forest[nr][nc]:\n visited[nr][nc] = True\n queue.append((nr, nc, d+1))\n \n return -1\n\t\t
3
0
[]
1
cut-off-trees-for-golf-event
python bfs
python-bfs-by-je390-uqza
whats the cost of path p \n\npath p == [u,v,w,x,y,z]\n\n\nits the cumulative total cost\n+ cost to get from u to v \n+ cost to get from v to w \n+ cost to get f
je390
NORMAL
2020-01-04T21:02:31.641191+00:00
2020-03-31T14:10:00.222454+00:00
1,100
false
whats the cost of path p \n```\npath p == [u,v,w,x,y,z]\n```\n\nits the cumulative total cost\n+ cost to get from u to v \n+ cost to get from v to w \n+ cost to get from w to x .\n+ etc...\n\nthe order we want is from smallest tree to highest\nthe nodes are actually coordinates, and their value in grid is used to rank them\n```\ns = [(i,j) for i in range(len(f)) for j in range(len(f[0])) if f[i][j]] \ns.sort(key = lambda x: f[x[0]][x[1]])\n```\nand we always start by (0,0)\n```\ns = [(0,0)] + s\n```\ncumul is the answer\n```\ncumul = 0\nfor u,v in zip(s,s[1:]): \n\tcumul += self.bfs(u,v,f)\n\tif cumul == float(\'inf\'): return -1\nreturn cumul\n```\n\nyou can walk passed uncut tree if, I was checking that the height would be strictly increasing from (0,0), but you can actually walk through a tree\nthe only forbidden cell is the zero\n\n\n\n\ncode\n```\nclass Solution(object):\n def cutOffTree(self, f):\n s = [(i,j) for i in range(len(f)) for j in range(len(f[0])) if f[i][j]] \n s.sort(key = lambda x: f[x[0]][x[1]])\n s = [(0,0)] + s\n cumul = 0\n for u,v in zip(s,s[1:]): \n cumul += self.bfs(u,v,f)\n if cumul == float(\'inf\'): return -1\n return cumul\n \n def bfs(self,source,target,grid):\n q,vis = collections.deque([(source,0)]),set([source])\n while(q):\n u,steps = q.popleft()\n if u == target: return steps\n for v in [(u[0]-1,u[1]), (u[0]+1,u[1]), (u[0],u[1]-1), (u[0],u[1]+1)]:\n if 0 <= v[0] < len(grid) and 0 <= v[1] < len(grid[0]) and grid[v[0]][v[1]] != 0 and v not in vis:\n vis.add(v)\n q.append((v,steps + 1))\n return +float(\'inf\')\n```
3
0
['Breadth-First Search', 'Python']
2
cut-off-trees-for-golf-event
Python / BFS - simple working solution
python-bfs-simple-working-solution-by-jl-86kw
\n def cutOffTree(self, forest: List[List[int]]) -> int:\n trees = []\n\n for i in range(len(forest)):\n for j in range(len(forest[0
jlee243
NORMAL
2019-07-22T16:08:26.929292+00:00
2019-07-22T16:08:26.929327+00:00
400
false
```\n def cutOffTree(self, forest: List[List[int]]) -> int:\n trees = []\n\n for i in range(len(forest)):\n for j in range(len(forest[0])):\n if forest[i][j] > 1:\n trees.append(forest[i][j])\n\n trees = sorted(trees)[::-1]\n start = [0,0]\n steps = [0]\n\n while trees:\n tree_loc = self.find_tree(trees.pop(), start[0], start[1], forest, steps)\n if not tree_loc:\n return -1\n else:\n start = tree_loc\n\n return steps[0]\n\n def find_tree(self, target, r, c, forest, steps):\n queue = [(r,c,0)]\n seen = set()\n while queue:\n r,c,step = queue.pop(0)\n if 0 <= r <= len(forest)-1 and 0 <= c <= len(forest[0]) - 1 and (r,c) not in seen and forest[r][c] >= 1:\n if forest[r][c] == target:\n steps[0] += step\n return [r,c]\n seen.add((r,c))\n queue.append((r+1,c,step+1))\n queue.append((r-1,c,step+1))\n queue.append((r,c+1,step+1))\n queue.append((r,c-1,step+1))\n\n return False\n```
3
1
[]
0
cut-off-trees-for-golf-event
Python solution with detailed explanation
python-solution-with-detailed-explanatio-6p79
Cut Off Trees for Golf Event https://leetcode.com/problems/cut-off-trees-for-golf-event/description/\n\nBFS based solution (in Python gives TLE)\n Use a priorit
gabbu
NORMAL
2017-09-11T04:17:20.406000+00:00
2017-09-11T04:17:20.406000+00:00
1,270
false
**Cut Off Trees for Golf Event** https://leetcode.com/problems/cut-off-trees-for-golf-event/description/\n\n**BFS based solution (in Python gives TLE)**\n* Use a priority queue to arrange all trees in ascending height order.\n* Then simply use BFS to find the minimum steps between consecutive trees.\n* Time complexity: O(m^2 * n^2)\n```\nfrom heapq import heappop, heappush\nfrom collections import deque\n\nclass Solution:\n def build_pq(self, forest):\n pq = []\n for i in range(len(forest)):\n for j in range(len(forest[0])):\n if forest[i][j] > 1:\n heappush(pq, (forest[i][j], i, j))\n return pq\n \n def process_level(self, forest, dq, seen, xdest, ydest):\n M,N = len(forest), len(forest[0])\n for _ in range(len(dq)):\n x2, y2 = dq.popleft()\n if x2 == xdest and y2 == ydest:\n return True\n for xn,yn in ((x2-1,y2),(x2+1,y2),(x2,y2-1),(x2,y2+1)):\n if 0<=xn<M and 0<=yn<N and forest[xn][yn] != 0 and (xn,yn) not in seen:\n dq.append((xn,yn))\n seen.add((xn,yn))\n return False\n \n def find_steps_bfs(self, forest, start, dest):\n dq = deque()\n dq.append((start[0], start[1]))\n seen = set()\n steps = 0\n while dq:\n found = self.process_level(forest, dq, seen, dest[0], dest[1])\n if found:\n break\n else:\n steps += 1\n return steps if found else -1\n \n def cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: int\n """\n pq = self.build_pq(forest)\n xstart, ystart, steps = 0, 0, 0\n while pq:\n ht, xdest, ydest = heappop(pq)\n curr_step = self.find_steps_bfs(forest, (xstart, ystart), (xdest, ydest))\n if curr_step == -1:\n return -1\n else:\n steps += curr_step\n xstart, ystart = xdest, ydest\n return steps \n```
3
1
[]
1
cut-off-trees-for-golf-event
C++ || BFS || Easy solution || Heap 👨🏻‍💻
c-bfs-easy-solution-heap-by-manishtomarl-74p6
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves cutting down trees in a forest, where the height of trees is repre
manishtomarleo21
NORMAL
2024-10-04T10:49:21.863260+00:00
2024-10-04T10:49:21.863298+00:00
344
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves cutting down trees in a forest, where the height of trees is represented by a 2D grid. You start at the top-left corner and can only walk in 4 directions: up, down, left, and right. The goal is to cut the trees in order of their height, so you need to navigate from one tree to the next and find the minimum steps needed to achieve this. If it\'s not possible to reach a tree, return -1.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sorting Trees by Height: First, collect all the tree positions in a priority queue sorted by height because trees must be cut in increasing order of their height.\n\n2. BFS for Shortest Path: To move from one tree to another, we perform a Breadth-First Search (BFS). BFS ensures that we find the shortest path between the two trees. If a path doesn\'t exist, return -1.\n\n3. Processing Trees: Start at the initial position (0,0). For each tree (in sorted order), run BFS to find the shortest path. After reaching the current tree, update your starting position and repeat until all trees are processed.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(T\xD7m\xD7n+m\xD7nlog(m\xD7n))\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(mxn)\n\n# Code\n```cpp []\nclass Solution {\nprivate:\n // Check if the cell (i, j) is within the bounds of the grid.\n bool isSafe(int i, int j, int m, int n) {\n return i >= 0 && i < m && j >= 0 && j < n;\n }\n\n // BFS function to find the shortest path from (currI, currJ) to (nextI, nextJ).\n int BFS(vector<vector<int>>& forest, int currI, int currJ, int nextI, int nextJ) {\n int m = forest.size();\n int n = forest[0].size();\n int step = 0;\n vector<vector<bool>> visited(m, vector<bool>(n, false));\n\n // Start BFS from the current position.\n visited[currI][currJ] = true;\n vector<vector<int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n queue<pair<int, int>> q;\n q.push({currI, currJ});\n\n // BFS loop\n while (!q.empty()) {\n int size = q.size();\n while (size--) {\n int i = q.front().first;\n int j = q.front().second;\n q.pop();\n\n // If we\'ve reached the target tree, return the number of steps.\n if (i == nextI && j == nextJ) return step;\n\n // Explore all four directions.\n for (auto& dir : directions) {\n int x = i + dir[0];\n int y = j + dir[1];\n\n // If it\'s a valid and unvisited cell, and it\'s not a blocked cell (forest[x][y] != 0).\n if (isSafe(x, y, m, n) && visited[x][y] == false && forest[x][y] != 0) {\n visited[x][y] = true;\n q.push({x, y});\n }\n }\n }\n step++; // Increment step count after processing all current level nodes.\n }\n\n // If the tree is unreachable, return a large value.\n return INT_MAX;\n }\n\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int m = forest.size();\n int n = forest[0].size();\n\n // Priority queue to store trees in increasing order of height.\n priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;\n\n // Insert all trees (value >= 2) into the priority queue with their coordinates.\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int num = forest[i][j];\n if (num >= 2) {\n pq.push({num, i, j});\n }\n }\n }\n\n int lastI = 0, lastJ = 0; // Start position at (0,0)\n int step = 0;\n\n // Process each tree in increasing order of height.\n while (!pq.empty()) {\n auto vec = pq.top();\n pq.pop();\n\n // Perform BFS to find the shortest path from the last position to the next tree.\n int pathFinder = BFS(forest, lastI, lastJ, vec[1], vec[2]);\n\n // If a tree is unreachable, return -1.\n if (pathFinder == INT_MAX) return -1;\n\n // Add the steps to the total and update the last position.\n step += pathFinder;\n lastI = vec[1];\n lastJ = vec[2];\n }\n\n return step; // Return the total number of steps.\n }\n};\n```
2
0
['Breadth-First Search', 'Heap (Priority Queue)', 'C++']
1
cut-off-trees-for-golf-event
sort as per the given numbers and keep the indexes later on do the multi source BFS
sort-as-per-the-given-numbers-and-keep-t-aobg
\nclass Solution {\npublic:\n \n int vis[54][54];\n void fill_v()\n {\n for(int i =0;i<54;i++)\n {\n for(int j=0;j<54;j++)\
mr_stark
NORMAL
2023-05-21T20:27:22.966775+00:00
2023-05-21T20:28:51.194171+00:00
457
false
```\nclass Solution {\npublic:\n \n int vis[54][54];\n void fill_v()\n {\n for(int i =0;i<54;i++)\n {\n for(int j=0;j<54;j++)\n {\n vis[i][j] = 0;\n }\n }\n }\n \n \n int bfs(int si, int sj, int ei, int ej,vector<vector<int>> &f)\n {\n queue<pair<int,pair<int,int>>> q;\n q.push({0,{si,sj}});\n int ans = -1;\n \n int n = f.size();\n int m = f[0].size();\n \n while(!q.empty())\n {\n int level = q.front().first;\n int i = q.front().second.first;\n int j = q.front().second.second;\n \n q.pop();\n if(vis[i][j])\n continue;\n \n vis[i][j] = 1;\n \n \n \n if(i == ei && j == ej)\n {\n return level;\n }\n \n if(i+1 < n && j<m && vis[i+1][j] == 0 && f[i+1][j])\n {\n q.push({level+1, {i+1, j}});\n }\n \n if(i < n && j+1<m && vis[i][j+1] == 0 && f[i][j+1])\n {\n q.push({level+1, {i, j+1}});\n }\n \n if(i-1>=0 && i-1 < n && j<m && vis[i-1][j] == 0 && f[i-1][j])\n {\n q.push({level+1, {i-1, j}});\n }\n \n if(j-1>=0 && i< n && j-1<m && vis[i][j-1] == 0 && f[i][j-1])\n {\n q.push({level+1, {i, j-1}});\n }\n }\n \n return ans;\n \n }\n \n int cutOffTree(vector<vector<int>>& f) {\n \n \n int n = f.size();\n int m = f[0].size();\n vector<pair<int,pair<int,int>>> v; \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(f[i][j]>1)\n v.push_back({f[i][j],{i,j}});\n }\n \n }\n \n v.push_back({0,{0,0}});\n int l = v.size();\n \n sort(v.begin(),v.end());\n int ans = 0;\n for(int i=0;i<l-1;i++)\n {\n fill_v();\n int si,sj,ei,ej;\n si = v[i].second.first;\n sj = v[i].second.second;\n \n ei = v[i+1].second.first;\n ej = v[i+1].second.second;\n \n int res = bfs( si, sj, ei, ej,f);\n if(res == -1)\n return res;\n ans+=res;\n }\n \n return ans;\n }\n};\n```
2
0
['C']
0
cut-off-trees-for-golf-event
Solution
solution-by-deleted_user-1dgu
C++ []\nclass Solution {\n static constexpr int DIR[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};\n struct Cell {\n short r : 8;\n short c : 8;\n
deleted_user
NORMAL
2023-04-17T13:18:14.832823+00:00
2023-04-17T13:48:06.111447+00:00
1,565
false
```C++ []\nclass Solution {\n static constexpr int DIR[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};\n struct Cell {\n short r : 8;\n short c : 8;\n };\n int doit(const vector<vector<int>>& forest, Cell start, vector<int> &curr, vector<int> &prev, vector<Cell> &bfs) {\n const int M = forest.size(), N = forest[0].size();\n int steps = 0;\n swap(curr, prev);\n fill(begin(curr), end(curr), -1);\n curr[start.r * N + start.c] = steps;\n if (prev[start.r * N + start.c] != -1) {\n return prev[start.r * N + start.c];\n }\n bfs.clear();\n bfs.push_back(start);\n while (!bfs.empty()) {\n int size = bfs.size();\n steps++;\n while (size--) {\n auto [r0, c0] = bfs[size];\n swap(bfs[size], bfs.back());\n bfs.pop_back();\n for (auto [dr, dc] : DIR) {\n short r1 = r0 + dr, c1 = c0 + dc;\n int pos = r1 * N + c1;\n if (r1 >= 0 && r1 < M && c1 >= 0 && c1 < N && forest[r1][c1] > 0 && curr[pos] == -1) {\n if (prev[pos] != -1) {\n return steps + prev[pos];\n }\n curr[pos] = steps;\n bfs.push_back({r1, c1});\n }\n }\n }\n }\n return -1;\n }\n int manhattan_distance(vector<Cell> &cells) {\n int result = 0;\n Cell prev{0, 0};\n for (auto &cell : cells) {\n result += abs(prev.r - cell.r) + abs(prev.c - cell.c);\n prev = cell;\n }\n return result;\n }\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n const int M = forest.size(), N = forest[0].size();\n if (forest[0][0] == 0) {\n return -1;\n }\n int obstacles = 0;\n vector<Cell> cells;\n cells.reserve(8);\n\n for (short r = 0; r < M; r++) {\n for (short c = 0; c < N; c++) {\n if (forest[r][c] > 1) {\n cells.push_back({r, c});\n } else if (forest[r][c] == 0) {\n obstacles++;\n }\n }\n }\n sort(begin(cells), end(cells), [&forest](const Cell &a, const Cell &b){\n return forest[a.r][a.c] < forest[b.r][b.c];\n });\n if (obstacles == 0) {\n return manhattan_distance(cells);\n }\n vector<int> curr(M * N, -1), prev = curr;\n curr[0] = 0;\n\n vector<Cell> bfs;\n bfs.reserve(8);\n\n int steps = 0;\n\n for (auto &cell : cells) {\n int result = doit(forest, cell, curr, prev, bfs);\n\n if (result != -1) {\n steps += result;\n } else {\n return -1;\n }\n }\n return steps;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n if forest[0][0] == 0 :\n return -1\n m = len(forest)\n n = len(forest[0])\n def distance(node1, node2):\n now = [node1]\n soon = []\n expanded = set()\n manhattan = abs(node1[0] - node2[0]) + abs(node1[1] - node2[1])\n detours = 0\n while True:\n if len(now) == 0:\n now = soon\n soon = []\n detours += 1\n node = now.pop()\n if node == node2:\n return manhattan + 2 * detours\n if node not in expanded:\n expanded.add(node)\n x, y = node\n if x - 1 >= 0 and forest[x - 1][y] >= 1:\n if x > node2[0]:\n now.append((x - 1, y))\n else:\n soon.append((x - 1, y))\n if y + 1 < n and forest[x][y + 1] >= 1:\n if y < node2[1]:\n now.append((x, y + 1))\n else:\n soon.append((x, y + 1))\n if x + 1 < m and forest[x + 1][y] >= 1:\n if x < node2[0]:\n now.append((x + 1, y))\n else:\n soon.append((x + 1, y))\n if y - 1 >= 0 and forest[x][y - 1] >= 1:\n if y > node2[1]:\n now.append((x, y - 1))\n else:\n soon.append((x, y - 1))\n trees = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n trees.append(((i, j), forest[i][j]))\n trees.sort(key=lambda x: x[1])\n can_reach = {(0, 0)}\n stack = [(0, 0)]\n while len(stack) > 0:\n x, y = stack.pop()\n if x - 1 >= 0 and forest[x - 1][y] >= 1 and (x - 1, y) not in can_reach:\n can_reach.add((x - 1, y))\n stack.append((x - 1, y))\n if y + 1 < n and forest[x][y + 1] >= 1 and (x, y + 1) not in can_reach:\n can_reach.add((x, y + 1))\n stack.append((x, y + 1))\n if x + 1 < m and forest[x + 1][y] >= 1 and (x + 1, y) not in can_reach:\n can_reach.add((x + 1, y))\n stack.append((x + 1, y))\n if y - 1 >= 0 and forest[x][y - 1] >= 1 and (x, y - 1) not in can_reach:\n can_reach.add((x, y - 1))\n stack.append((x, y - 1))\n for t in trees:\n if t[0] not in can_reach:\n return -1\n start = (0, 0)\n num_step = 0\n for t in trees: \n num_step += distance(start, t[0])\n forest[t[0][0]][t[0][1]] = 1\n start = t[0]\n return num_step\n```\n\n```Java []\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1])));\n for(int i=0;i<forest.size();i++){\n for(int j=0;j<forest.get(0).size();j++){\n if(forest.get(i).get(j)>1)\n pq.add(new int[]{i,j});\n }\n }\n int ans=0;\n int curr[]={0,0};\n while(pq.size()>0){\n int[] temp=pq.poll();\n int dis=calcDis(forest,curr,temp);\n if(dis==-1)\n return -1;\n ans+=dis;\n curr=temp;\n }\n return ans;\n }\n int calcDis(List<List<Integer>> forest,int start[],int end[]){\n int n=forest.size(),m=forest.get(0).size();\n boolean vis[][]=new boolean[n][m];\n Queue<int[]> queue=new LinkedList<>();\n queue.add(start);\n vis[start[0]][start[1]]=true;\n int dis=0;\n while(queue.size()>0){\n int len =queue.size();\n while(len-->0){\n int temp[]=queue.remove();\n int r=temp[0],c=temp[1];\n if(r==end[0] && c==end[1])\n return dis;\n if(r+1<n && !vis[r+1][c] && forest.get(r+1).get(c)!=0){\n queue.add(new int[]{r+1,c});\n vis[r+1][c]=true;\n }if(r-1>=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){\n queue.add(new int[]{r-1,c});\n vis[r-1][c]=true;\n }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){\n queue.add(new int[]{r,c-1});\n vis[r][c-1]=true;\n }if(c+1<m && !vis[r][c+1] && forest.get(r).get(c+1)!=0){\n queue.add(new int[]{r,c+1});\n vis[r][c+1]=true;\n }\n }\n dis++;\n }\n return -1;\n }\n}\n```\n
2
0
['C++', 'Java', 'Python3']
0
cut-off-trees-for-golf-event
675: Solution with step by step explanation
675-solution-with-step-by-step-explanati-m83d
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. We first initialize the size of the forest m and n. We also create an
Marlen09
NORMAL
2023-03-19T18:11:44.772384+00:00
2023-03-19T18:11:44.772417+00:00
1,398
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We first initialize the size of the forest m and n. We also create an empty list called trees which will contain tuples of (height, x, y) where x and y are the coordinates of the tree in the forest.\n\n2. We iterate through every cell in the forest and if the value is greater than 1, we append a tuple of (height, x, y) to the trees list. We sort the list by the height of the trees in ascending order.\n\n3. We define a bfs function which takes in the starting coordinates sx and sy, and the target coordinates tx and ty. We use a heap to implement Dijkstra\'s algorithm for finding the shortest path. We keep track of the minimum distance d, current coordinates x and y, and push the tuple (d, x, y) into the heap.\n\n4. We create a visited set to keep track of cells that have been visited. We add the starting coordinates to the set.\n\n5. While the heap is not empty, we pop the cell with the minimum distance d from the heap. If the current coordinates are the target coordinates, we return the minimum distance d.\n\n6. Otherwise, we iterate through all possible directions (north, east, south, west) and check if the next cell is within the boundaries of the forest, not in the visited set, and not blocked by a tree. If the conditions are met, we add the next cell to the visited set and push the tuple (d+1, nx, ny) into the heap.\n\n7. If the target coordinates cannot be reached, we return -1.\n\n8. We initialize ans to 0, and the starting coordinates sx and sy to (0, 0).\n\n9. We iterate through every tree in the trees list in ascending order of height. For each tree,\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 cutOffTree(self, forest: List[List[int]]) -> int:\n m, n = len(forest), len(forest[0])\n trees = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n trees.append((forest[i][j], i, j))\n trees.sort()\n\n def bfs(sx, sy, tx, ty):\n queue = [(0, sx, sy)]\n visited = set()\n visited.add((sx, sy))\n while queue:\n d, x, y = heapq.heappop(queue)\n if x == tx and y == ty:\n return d\n for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n nx, ny = x + dx, y + dy\n if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited and forest[nx][ny]:\n visited.add((nx, ny))\n heapq.heappush(queue, (d+1, nx, ny))\n return -1\n\n ans = 0\n sx, sy = 0, 0\n for _, tx, ty in trees:\n d = bfs(sx, sy, tx, ty)\n if d == -1:\n return -1\n ans += d\n sx, sy = tx, ty\n return ans\n\n```
2
0
['Array', 'Breadth-First Search', 'Heap (Priority Queue)', 'Python', 'Python3']
2
cut-off-trees-for-golf-event
C++ || Commented Explanation || Easy to Understand || BFS + Greedy
c-commented-explanation-easy-to-understa-e3nm
\n/*\n\n 0 --> obstacle\n 1 --> empty cell\n>1 --> tree\'s height\n\n North , East , South , West --> Moves Possible\n \n We can cut off all the trees , if and
anu_2021
NORMAL
2022-10-05T18:35:48.499018+00:00
2022-10-05T18:35:48.499066+00:00
564
false
```\n/*\n\n 0 --> obstacle\n 1 --> empty cell\n>1 --> tree\'s height\n\n North , East , South , West --> Moves Possible\n \n We can cut off all the trees , if and only if there exists a\n path from the current tree to the next greater tree value.\n\n We will sort the tree\'s according to their values and then do a\n bfs traversal b/w adjacent trees and calculate the shortest \n distance b/w them , if there is no path possible , then return \n -1, otherwise at the end of the program return the summation of \n those distances.\n \n T.C : O(M*N*M*N)\n S.C : O(M*N)\n\n*/\n\n// Build a Tree Cell Structure for simplicity sake //\n\nstruct Tree{\n \n public:\n \n int value;\n int x;\n int y;\n \n};\n\n// Helps to sort the trees on the basis of their values //\n\nbool static comp(const Tree&x,const Tree&y){\n \n return x.value < y.value;\n \n}\n\n// 4-directional coordinates //\n\nint dx[4] = {0,0,1,-1};\nint dy[4] = {1,-1,0,0};\n\nint visited[52][52];\n\nint bfs_traversal(int src1,int src2,int dest1,int dest2,vector<vector<int>>&forest){\n \n int m = forest.size();\n int n = forest[0].size();\n \n // Reset the visited array //\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n visited[i][j] = 0;\n }\n }\n \n // Data structure widely used for BFS Traversal //\n \n queue<pair<int,int>>q;\n \n // Single Source BFS //\n \n q.push({src1,src2});\n \n int lvl = 0;\n \n while(!q.empty()){\n \n int sz = q.size();\n \n while(sz--){\n \n auto curr = q.front();\n q.pop();\n \n int x = curr.first;\n int y = curr.second;\n \n if(x==dest1 && y==dest2){\n return lvl;\n }\n \n if(visited[x][y]) continue;\n \n visited[x][y] = 1;\n \n for(int dir=0;dir<4;dir++){\n \n int nx = x + dx[dir];\n int ny = y + dy[dir];\n \n if(nx>=0 && nx<m && ny>=0 && ny<n && !visited[nx][ny] && forest[nx][ny]){\n \n q.push({nx,ny});\n \n }\n \n }\n \n }\n \n lvl++;\n \n }\n \n return -1;\n \n}\n\nclass Solution {\npublic:\n \n int cutOffTree(vector<vector<int>>& forest) {\n \n int m=forest.size();\n int n=forest[0].size();\n \n vector<Tree>vec;\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(forest[i][j]>1){\n vec.push_back({forest[i][j],i,j});\n }\n }\n }\n \n // Starting Point - By default //\n \n vec.push_back({0,0,0});\n \n // Sort on the basis of the tree values //\n \n sort(vec.begin(),vec.end(),comp);\n \n int ans = 0;\n \n // BFS Traversal b/w adjacent trees //\n \n for(int i=0;i<vec.size()-1;i++){\n \n int curr = bfs_traversal(vec[i].x,vec[i].y,vec[i+1].x,vec[i+1].y,forest);\n \n // If there doesn\'t exist a single path b/w adjacent trees , then simple return -1 (invalid sequence) //\n \n if(curr<0){\n return -1;\n }\n \n ans += curr;\n \n }\n \n return ans;\n \n }\n};\n```
2
0
['Greedy', 'Breadth-First Search', 'C']
0
cut-off-trees-for-golf-event
Use BFS and Sorting
use-bfs-and-sorting-by-optimal_ns65-j3wv
\n int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};\n int solve(int s,int e,int x,int y,vector>& forest){\n if(s==x && e==y) return 0;\n \n
Optimal_NS65
NORMAL
2022-09-16T16:21:48.355989+00:00
2022-10-02T07:55:07.311895+00:00
394
false
\n int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};\n int solve(int s,int e,int x,int y,vector<vector<int>>& forest){\n if(s==x && e==y) return 0;\n \n int n=forest.size();\n int m=forest[0].size();\n queue<pair<int,int>> q;\n int vis[n][m];\n memset(vis,0,sizeof(vis));\n \n vis[s][e]=1;\n q.push({s,e});\n int count=0;\n while(!q.empty()){\n count++;\n int nn=q.size();\n while(nn--){\n auto it=q.front();\n q.pop();\n \n for(int i=0;i<4;i++){\n int n_x=it.first+dir[i][0];\n int n_y=it.second+dir[i][1];\n if(n_x<0 || n_y<0 || n_x>=n || n_y>=m || vis[n_x][n_y]==1 || forest[n_x][n_y]==0){\n continue;\n }\n q.push({n_x,n_y});\n vis[n_x][n_y]=1;\n if(n_x==x && n_y==y) return count;\n \n }\n }\n }\n return -1;\n }\n \n int cutOffTree(vector<vector<int>>& forest) {\n \n for(int i=0;i<forest.size();i++){\n for(int j=0;j<forest[i].size();j++){\n if(forest[i][j]>1){\n ans.push_back({forest[i][j],i,j});\n }\n }\n }\n sort(ans.begin(),ans.end());\n int s=0,e=0;\n int res=0;\n for(auto &it:ans){\n int d=solve(s,e,it[1],it[2],forest);\n if(d==-1){\n return -1;\n }\n res+=d;\n s=it[1];\n e=it[2];\n }\n return res;\n \n }
2
0
['Breadth-First Search']
0
cut-off-trees-for-golf-event
java ez 2 understand
java-ez-2-understand-by-ab06ayush-mrkb
```\nclass Solution {\n //approach: 1st store all the positions in the min heap acc. to their height\n //now start removing the elements from the heap and
ab06ayush
NORMAL
2022-08-04T20:29:20.579575+00:00
2022-08-04T20:29:20.579612+00:00
614
false
```\nclass Solution {\n //approach: 1st store all the positions in the min heap acc. to their height\n //now start removing the elements from the heap and calculate their dis using bfs\n // if at any point we cann\'t reach at the next position return -1;\n // else keep on adding the distances and return;\n public int cutOffTree(List<List<Integer>> forest) {\n PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1])));\n for(int i=0;i<forest.size();i++){\n for(int j=0;j<forest.get(0).size();j++){\n if(forest.get(i).get(j)>1)\n pq.add(new int[]{i,j});\n }\n }\n int ans=0;\n int curr[]={0,0};\n while(pq.size()>0){\n int[] temp=pq.poll();\n int dis=calcDis(forest,curr,temp);\n //System.out.println(dis+" "+temp.height);\n if(dis==-1)\n return -1;\n ans+=dis;\n curr=temp;\n }\n return ans;\n }\n int calcDis(List<List<Integer>> forest,int start[],int end[]){\n int n=forest.size(),m=forest.get(0).size();\n boolean vis[][]=new boolean[n][m];\n Queue<int[]> queue=new LinkedList<>();\n queue.add(start);\n vis[start[0]][start[1]]=true;\n int dis=0;\n while(queue.size()>0){\n int len =queue.size();\n while(len-->0){\n int temp[]=queue.remove();\n int r=temp[0],c=temp[1];\n if(r==end[0] && c==end[1])\n return dis;\n if(r+1<n && !vis[r+1][c] && forest.get(r+1).get(c)!=0){\n queue.add(new int[]{r+1,c});\n vis[r+1][c]=true;\n }if(r-1>=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){\n queue.add(new int[]{r-1,c});\n vis[r-1][c]=true;\n }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){\n queue.add(new int[]{r,c-1});\n vis[r][c-1]=true;\n }if(c+1<m && !vis[r][c+1] && forest.get(r).get(c+1)!=0){\n queue.add(new int[]{r,c+1});\n vis[r][c+1]=true;\n }\n }\n dis++;\n }\n return -1;\n \n }\n}
2
0
['Breadth-First Search', 'Heap (Priority Queue)', 'Java']
0
cut-off-trees-for-golf-event
PQ + BFS (easy explanation)
pq-bfs-easy-explanation-by-jainakshat425-umut
To cut the shortest trees first - \n- add all the tree with their position in a priority queue (min heap).\n\nTo find the min no. of steps to cut all trees star
jainakshat425
NORMAL
2022-07-31T07:17:20.919422+00:00
2022-07-31T07:17:20.919469+00:00
269
false
To cut the shortest trees first - \n- add all the tree with their position in a priority queue (min heap).\n\nTo find the min no. of steps to cut all trees starting from (0,0)\n- Set the src to (0,0)\n- Get position of shortest height tree, let\'s say (x,y)\n- BFS to find min steps to reach from (0,0) to (x,y)\n- update src to (x,y) and repeat steps for the next shortest tree\n\n```\nclass Solution {\n private static final int[][] DIR = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}};\n \n public int cutOffTree(List<List<Integer>> forest) {\n int m = forest.size(), n = forest.get(0).size();\n // [tree height, row, col]\n PriorityQueue<int[]> trees = new PriorityQueue<int[]>(\n (a,b) -> Integer.compare(a[0], b[0]));\n \n for(int i=0; i<m; i++) \n for(int j=0; j<n; j++) {\n int ht = forest.get(i).get(j);\n if( ht > 1 )\n trees.offer(new int[]{ht, i, j});\n }\n \n int ans = 0;\n int currX = 0, currY = 0;\n \n while( !trees.isEmpty() ) {\n int i = trees.peek()[1], j = trees.poll()[2];\n \n int steps = bfs(currX, currY, i, j, forest);\n if( steps == -1 )\n return -1;\n ans += steps;\n currX = i;\n currY = j;\n }\n return ans;\n }\n \n private int bfs(int srcRow, int srcCol, int destRow, int destCol, List<List<Integer>> forest) {\n int m = forest.size(), n = forest.get(0).size();\n boolean[][] visited = new boolean[m][n];\n Queue<int[]> queue = new LinkedList();\n int steps = 0;\n\n queue.offer(new int[]{ srcRow, srcCol });\n visited[srcRow][srcCol] = true;\n \n while( !queue.isEmpty() ) {\n int size = queue.size();\n \n while( size-- > 0 ) {\n int i = queue.peek()[0];\n int j = queue.peek()[1];\n queue.poll();\n \n if( i == destRow && j == destCol )\n return steps;\n \n for(int[] dir : DIR) {\n int di = i + dir[0];\n int dj = j + dir[1];\n\n if( di < 0 || dj < 0 || di == m || dj == n )\n continue;\n \n if( visited[di][dj] || forest.get(di).get(dj) == 0 ) \n continue;\n \n queue.offer(new int[]{di, dj});\n visited[di][dj] = true;\n }\n }\n steps++;\n }\n return -1;\n }\n}\n```
2
0
['Java']
0
cut-off-trees-for-golf-event
sort(heap) + BFS, good job leetcode admin
sortheap-bfs-good-job-leetcode-admin-by-fuxki
Hi LeetCode Admin, congratulation, you made every python code using sort(heap) + BFS TLE again. Good job on wasting people\'s time. I thought I did something wr
hsZh
NORMAL
2022-05-30T13:43:08.691240+00:00
2022-05-30T13:43:08.691271+00:00
345
false
Hi LeetCode Admin, congratulation, you made every python code using sort(heap) + BFS TLE **again**. Good job on wasting people\'s time. I thought I did something wrong, but checked some code from discuss, same TLE. \n\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n m, n = len(forest), len(forest[0])\n if forest[0][0] == 0:\n return -1\n # Have priority queue that stores (height,x,y) for each tree in order of min to max.\n # Use BFS to find the next available smallest height in priority queue.\n heap = []\n \n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n heappush(heap, (forest[i][j], i, j))\n \n \n def bfs(sx, sy, tx, ty):\n \n visited = set()\n visited.add((sx, sy))\n \n queue = deque()\n queue.append((sx, sy))\n d = 0\n while queue:\n for _ in range(len(queue)):\n cx, cy = queue.popleft()\n if cx == tx and cy == ty:\n forest[cx][cy] = 1\n return d\n\n for nx, ny in ((cx+1, cy), (cx-1, cy), (cx, cy-1), (cx, cy+1)):\n if 0 <= nx < m and 0 <= ny < n and forest[nx][ny] != 0 and(nx, ny) not in visited:\n queue.append((nx, ny))\n visited.add((nx, ny))\n\n d += 1\n return -1\n \n ans = 0\n prev_x, prev_y = 0, 0\n while heap:\n _, x, y = heappop(heap)\n \n step = bfs(prev_x, prev_y, x, y)\n if step == -1:\n return -1\n ans += step\n prev_x, prev_y = x, y\n return ans\n \n```
2
0
[]
1
cut-off-trees-for-golf-event
READABLE CODE with FUNCTIONS/COMMENTS ~ Python Solution BFS with Priority Queue
readable-code-with-functionscomments-pyt-o2kj
This code is written in a way that should be understandable by most Leetcoders :)\nI\'d recommend reading it in the following order:\nminStepsToCell, getPossibl
thanasiz
NORMAL
2022-02-26T22:38:29.596833+00:00
2022-02-28T13:09:26.414196+00:00
378
false
This code is written in a way that should be understandable by most Leetcoders :)\nI\'d recommend reading it in the following order:\nminStepsToCell, getPossibleMoves (standard bfs)\ncreateTreeLocationsPriorityQueue,getNextTreeLocation (priority queue / function to feed us the next tree location)\ncutOffTree -> logic that combines the two concepts (bfs + priority queue)\n\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n self.createTreeLocationsPriorityQueue(forest)\n steps = 0\n treeLoc = self.getNextTreeLocation()\n currLoc = (0,0)\n while treeLoc != -1: \n\t\t#if there are no more trees in the pq this means that we\'ve cut down all the trees and should return the sum of the steps taken\n\t\t#so in every loop we "cut" the next tree (move to the location of the next tree), if we can\'t we return -1 as per the problem statement.\n\t\t\n costToTree = self.minStepsToCell(forest,currLoc,treeLoc)\n if costToTree == -1:\n return -1\n steps += costToTree\n currLoc = treeLoc\n treeLoc = self.getNextTreeLocation()\n return steps\n \n def getNextTreeLocation(self):\n\t#simply pops the next tree from the tree priority queue and returns its location\n if self.treePQ:\n height,i,j = heapq.heappop(self.treePQ)\n return (i,j)\n return -1\n \n def createTreeLocationsPriorityQueue(self,forest):\n\t#puts trees in a priority queue with the following format (treeheight,i,j)\n\t#when removing trees from the pq they will be removed shortest first,\n\t#this helps us easily get the location of the next tree to cut down.\n self.treePQ = []\n \n for i in range(len(forest)):\n for j in range(len(forest[0])):\n if forest[i][j] > 1:\n heapq.heappush(self.treePQ,(forest[i][j],i,j))\n \n def minStepsToCell(self,forest,currLoc,targetLoc):\n\t#just a regular BFS to find the minimum distance from one location to another.\n\t#if we can\'t reach our destination we return -1\n explored = set()\n q = [currLoc]\n steps = 0\n while q:\n nlq = []\n \n for loc in q:\n if loc == targetLoc:\n return steps\n if loc not in explored:\n explored.add(loc)\n nlq.extend(self.getPossibleMoves(forest,loc))\n \n steps += 1\n q = nlq\n return -1\n \n def getPossibleMoves(self,forest,loc):\n\t#Simply get possible moves (can move to cells that are not \'0\'\n i,j = loc\n moves = []\n if i > 0 and forest[i-1][j]:\n moves.append((i-1,j))\n if i < len(forest)-1 and forest[i+1][j]:\n moves.append((i+1,j))\n if j > 0 and forest[i][j-1]:\n moves.append((i,j-1))\n if j < len(forest[0])-1 and forest[i][j+1]:\n moves.append((i,j+1))\n return moves\n```
2
0
['Breadth-First Search', 'Heap (Priority Queue)', 'Python']
0
cut-off-trees-for-golf-event
Python BFS, No TLE, Easy to Understand
python-bfs-no-tle-easy-to-understand-by-kv8dm
This solution would get TLE if we used visited set instead of discovered because the queue will contain many duplicates if keep enqueing nodes until they\'ve be
klaythompson
NORMAL
2022-02-03T23:48:12.287507+00:00
2022-02-03T23:48:12.287559+00:00
496
false
This solution would get TLE if we used `visited` set instead of `discovered` because the queue will contain many duplicates if keep enqueing nodes until they\'ve been explored.\n\n```\nBLOCKED = 0\n\n\nclass DisjointNodesError(Exception):\n pass\n\n\nclass Solution:\n """\n we want to minimize the number of steps: ie path length\n we need to cut down trees in order from shortest to tallest\n\n find shortest path from start (0, 0) to shortest tree\n then find shortest path to each tree in sorted order\n summing paths the entire time\n\t\n\tall moves: north east west south => cost 1\n unweighted graph, bfs will give us the shortest path between any two points\n\t\n if we cannot get to a tree because the trees are disjoint return -1\n we shouldn\'t need to check beforehand whether or not trees are disjoint because we will find out during breadth first search\n\n first, sort trees by height so we know order to target them in => N logN\n then do bfs between each tree in sorted order => bfs O(n) * # trees n\n O(n^2)\n """\n\n def __init__(self):\n self.grid = [[]]\n self.left_bound = -1\n self.top_bound = -1\n self.bottom_bound = 0\n self.right_bound = 0\n\n def get_neighbors(self, node):\n r, c = node\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n neighbors = []\n for dr, dc in directions:\n if self.top_bound < r + dr < self.bottom_bound and self.left_bound < c + dc < self.right_bound:\n if self.grid[r + dr][c + dc] != BLOCKED:\n neighbors.append((r + dr, c + dc))\n return neighbors\n\n def bfs(self, start, end):\n discovered = set()\n queue = deque([(start, 0)])\n while queue:\n current, distance = queue.popleft()\n if current == end:\n return distance\n for neighbor in self.get_neighbors(current):\n if neighbor not in discovered:\n queue.append((neighbor, distance + 1))\n # use discovered instead of visited so we don\'t add duplicate vertices to queue\n discovered.add(neighbor)\n raise DisjointNodesError()\n\n def cutOffTree(self, forest: List[List[int]]) -> int:\n self.grid = forest\n self.bottom_bound = len(forest)\n self.right_bound = len(forest[0])\n trees = []\n # gather trees\n for r, row in enumerate(forest):\n for c, height in enumerate(row):\n if height > 1:\n trees.append((height, r, c))\n # sort trees\n trees.sort(key=lambda x: x[0])\n num_steps = 0\n # find shortest path between trees, sum path length\n start = (0, 0)\n for idx in range(0, len(trees)):\n height, r, c = trees[idx]\n next_tree = (r, c)\n try:\n distance = self.bfs(start, next_tree)\n except DisjointNodesError:\n return -1\n num_steps += distance\n start = next_tree\n return num_steps\n\t\t```
2
0
['Breadth-First Search', 'Python']
0
cut-off-trees-for-golf-event
Very Clean JAVA BFS Solution .
very-clean-java-bfs-solution-by-anshulpr-z2a4
BFS is used to find shortest path between src and destination, and PriorityQueue is used to find destinations..\n\'\'\'\n public int cutOffTree(List> forest)
anshulpro27
NORMAL
2022-01-21T13:53:34.416051+00:00
2022-01-21T13:53:34.416087+00:00
369
false
BFS is used to find shortest path between src and destination, and PriorityQueue is used to find destinations..\n\'\'\'\n public int cutOffTree(List<List<Integer>> forest) {\n \n int n = forest.size();\n int m = forest.get(0).size();\n int dir[][]= {{1,0},{0,1},{-1,0},{0,-1}}; \n \n PriorityQueue<Integer> minheap =new PriorityQueue<>(); \n \n for(List<Integer> al : forest) for(int val : al) if(val>1) minheap.add(val);\n \n int result=0;\n int [] src={0,0}; \n \n while(minheap.size()>0)\n {\n boolean vis [][] =new boolean[n][m];\n \n Queue<int[]> q =new LinkedList<>();\n \n q.add(new int[]{src[0],src[1],0});\n int target = minheap.remove(),ans=-1; \n \n while(!q.isEmpty())\n {\n int a [] = q.remove(); \n \n if(vis[a[0]][a[1]]) continue; \n vis[a[0]][a[1]] =true;\n \n //check for target\n if(forest.get(a[0]).get(a[1])==target) \n {\n src[0]=a[0]; \n src[1]=a[1];\n ans = a[2]; \n break; \n }\n \n for(int b[] : dir)\n {\n int r=a[0]+b[0];\n int c =a[1]+b[1];\n \n if(r<0 || r>=n || c<0 || c>=m || vis[r][c] || forest.get(r).get(c)==0) continue;\n \n q.add(new int[]{r,c,a[2]+1});\n } \n \n }\n \n if(ans==-1) return -1;\n \n result+=ans; \n }\n \n return result;\n }\n\'\'\'
2
1
[]
0
cut-off-trees-for-golf-event
Java BFS
java-bfs-by-veeralbhagat-okns
\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n if (forest == null || forest.size() == 0 || forest.get(0).size() == 0) {\n
veeralbhagat
NORMAL
2021-10-25T08:39:08.926003+00:00
2021-10-25T23:21:32.133068+00:00
194
false
```\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n if (forest == null || forest.size() == 0 || forest.get(0).size() == 0) {\n return -1;\n }\n \n int[][] matrix = new int[forest.size()][forest.get(0).size()];\n List<Integer> trees = new ArrayList<>();\n \n for (int i = 0; i < forest.size(); i++) {\n List<Integer> list = forest.get(i);\n for (int j = 0; j < list.size(); j++) {\n matrix[i][j] = list.get(j);\n if (matrix[i][j] > 1) {\n trees.add(matrix[i][j]);\n }\n }\n }\n \n Collections.sort(trees);\n int row = 0, col = 0;\n int steps = 0;\n \n for (Integer tree: trees) {\n boolean[][] visited = new boolean[matrix.length][matrix[0].length];\n int[] result = cut(matrix, visited, row, col, tree);\n \n if (result[0] == 1) {\n steps += result[1];\n row = result[2];\n col = result[3];\n } else {\n return -1;\n }\n }\n return steps;\n }\n \n private int[] cut(int[][] matrix, boolean[][] visited, int row, int col, int tree) {\n if (matrix[row][col] == tree) {\n matrix[row][col] = 1;\n return new int[] {1, 0, row, col};\n }\n \n Queue<String> q = new LinkedList<>();\n q.add(row + "_" + col);\n visited[row][col] = true;\n q.add(null);\n \n int steps = 0;\n \n while (!q.isEmpty()) {\n String current = q.remove();\n if (current == null) {\n if (!q.isEmpty()) {\n q.add(null);\n }\n steps++;\n continue;\n }\n \n String[] parts = current.split("_");\n row = Integer.parseInt(parts[0]);\n col = Integer.parseInt(parts[1]);\n if (matrix[row][col] == tree) {\n return new int[] {1, steps, row, col};\n }\n \n if (isValidCell(matrix, visited, row - 1, col)) {\n q.add((row - 1) + "_" + (col));\n visited[row - 1][col] = true;\n }\n if (isValidCell(matrix, visited, row + 1, col)) {\n q.add((row + 1) + "_" + (col));\n visited[row + 1][col] = true;\n }\n if (isValidCell(matrix, visited, row, col - 1)) {\n q.add((row) + "_" + (col - 1));\n visited[row][col - 1] = true;\n }\n if (isValidCell(matrix, visited, row, col + 1)) {\n q.add((row) + "_" + (col + 1));\n visited[row][col + 1] = true;\n }\n }\n return new int[] {0, 0, row, col};\n \n }\n \n private boolean isValidCell(int[][] matrix, boolean[][] visited, int row, int col) {\n return row >= 0 && col >= 0 && row < matrix.length && col < matrix[0].length && matrix[row][col] != 0 && !visited[row][col];\n }\n}\n```
2
0
[]
0
cut-off-trees-for-golf-event
[Java] Sorting + BFS
java-sorting-bfs-by-standanddeliver-hbty
Idea: Find the order of trees you need to find, BFS between each of the two points to find shortest path between each consective pair of trees (ie shortest path
standanddeliver
NORMAL
2021-08-25T20:51:38.908889+00:00
2021-08-25T20:51:38.908930+00:00
291
false
Idea: Find the order of trees you need to find, BFS between each of the two points to find shortest path between each consective pair of trees (ie shortest path between x1 and x2, then x2 and x3 where xi comes before xj if i < j).\n\n```\nclass Solution {\n class Triple{\n int val;\n int row;\n int col;\n public Triple (int val, int row, int col){\n this.val = val;\n this.row = row;\n this.col = col;\n }\n }\n class TripleComparator implements Comparator<Triple>{\n public int compare(Triple a, Triple b){\n return a.val - b.val;\n }\n }\n public int cutOffTree(List<List<Integer>> forest) {\n List<Triple> trees = new ArrayList<>();\n for(int i = 0; i < forest.size(); i++){\n for(int j = 0; j < forest.get(i).size(); j++){\n if(forest.get(i).get(j) > 1) trees.add(new Triple(forest.get(i).get(j), i, j));\n }\n }\n Collections.sort(trees, new TripleComparator());\n int[][] directions = new int[][] {{1,0}, {-1,0}, {0,-1}, {0,1}};\n int totalDistance = 0;\n Triple pastTree = new Triple(0,0,0);\n for(int i = 0; i < trees.size(); i++){\n Triple currTree = trees.get(i);\n int distance = findNextTree(forest, pastTree.row, pastTree.col, currTree.row, currTree.col, directions);\n if(distance == -1) return -1;\n totalDistance += distance;\n pastTree = currTree; \n }\n return totalDistance; \n }\n //number of edges between nodes, else -1 if unreachable \n //bfs gives shortest path from one node to another we do this for every pair of nodes\n private int findNextTree(List<List<Integer>> forest, int sr, int sc, int dr, int dc, int[][] directions){\n boolean[][] visited = new boolean[forest.size()][forest.get(0).size()];\n Queue<Triple> bfsQ = new LinkedList<>();\n bfsQ.offer(new Triple(forest.get(sr).get(sc), sr, sc));\n int level = -1;\n while(!bfsQ.isEmpty()){\n int qSize = bfsQ.size();\n while(qSize > 0){\n qSize--;\n Triple currNode = bfsQ.poll();\n if(currNode.row == dr && currNode.col == dc) {\n level++; \n return level;\n }\n for(int[] dir : directions){\n int nr = dir[0] + currNode.row;\n int nc = dir[1] + currNode.col;\n if(nr < 0 || nr > forest.size() - 1 || nc < 0 || nc > forest.get(nr).size()-1) continue;\n if(visited[nr][nc] || forest.get(nr).get(nc) < 1) continue;\n bfsQ.offer(new Triple(forest.get(nr).get(nc), nr, nc));\n visited[nr][nc] = true; \n }\n }\n level ++; \n }\n return -1; \n }\n \n \n}\n```
2
0
[]
0
cut-off-trees-for-golf-event
C++ || Clean and Simple || BFS || With Proper Comments
c-clean-and-simple-bfs-with-proper-comme-buvz
\nclass Solution {\npublic:\n int sx=0,sy=0;\n vector<vector<int>> offsets={{1,0},{0,1},{-1,0},{0,-1}};\n int cutOffTree(vector<vector<int>>& forest) {
intruder_110
NORMAL
2021-07-31T07:11:13.896561+00:00
2021-07-31T07:11:13.896622+00:00
477
false
```\nclass Solution {\npublic:\n int sx=0,sy=0;\n vector<vector<int>> offsets={{1,0},{0,1},{-1,0},{0,-1}};\n int cutOffTree(vector<vector<int>>& forest) {\n \n if(forest[0][0]==0)\n return -1;\n \n //first get heights of all the trees.\n vector<int> tree_heights;\n for(int i=0;i<forest.size();i++){\n for(int j=0;j<forest.at(0).size();j++){\n if(forest[i][j]!=1&&forest[i][j]!=0)\n tree_heights.push_back(forest[i][j]);\n }\n }\n \n //sort them (smaller to larger)\n sort(tree_heights.begin(),tree_heights.end());\n vector<vector<int>> temp;\n \n int total_steps=0,target;\n //loop that will find the next tree which we have to cut. and after finding that tree\n // we add the distance to total_distance and change the next tree(target) and update the forest vector\n for(int i=0;i<tree_heights.size();i++){\n\t\t\n target=tree_heights[i];\n temp=forest;\n int h=find_tree(sx,sy,target,temp);\n if(h==-1){\n return -1;\n }\n \n\t\t total_steps+=h;\n forest[sx][sy]=1;\n }\n return total_steps;\n }\n \n \n //this function finds tree with a given height from a starting point.\n\t//function itself is pretty standard BFS implementation.\n int find_tree(int xi,int yi,int target,vector<vector<int>>&temp){\n \n\t\t//corner case\n if(temp[xi][yi]==target){\n sx=xi;\n sy=yi;\n return 0;\n }\n \n queue<pair<int,int>> q;\n q.push({xi,yi});\n \n int current_steps=1;\n \n while(!q.empty()){\n int l=q.size();\n for(int z=0;z<l;z++){\n auto[i,j]=q.front();\n q.pop();\n \n for(int m=0;m<4;m++){\n \n int x=i-offsets[m][0];\n int y=j-offsets[m][1];\n \n if(x<0||y<0||x>=temp.size()||y>=temp.at(0).size()||temp[x][y]==0||temp[x][y]==-1)\n continue;\n \n if(temp[x][y]==target){\n sx=x;\n sy=y;\n return current_steps;\n }\n \n temp[x][y]=-1;\n q.push({x,y});\n }\n }\n current_steps++;\n }\n return -1;\n } \n};\n```
2
0
[]
0
cut-off-trees-for-golf-event
JAVA - BFS with Sorted Trees - Clean with comments
java-bfs-with-sorted-trees-clean-with-co-t36o
\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n \n //1) put all tree\'s into a list\n //2) sort the tree list
grumpygramper
NORMAL
2021-06-15T18:36:41.177886+00:00
2021-06-15T18:36:56.434580+00:00
184
false
```\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n \n //1) put all tree\'s into a list\n //2) sort the tree list by smallest\n //3) from idx (0,0) cut down all the trees by getting the next smallest tree from the list\n //4) call bfs to count the steps from current starting index until the next smallest tree\n \n //so if you can make it from the beginning to the smallest tree. count the steps at that tree as the new starting point to get to the next smallest\n \n List<int[]> trees = new ArrayList<>();\n \n int R = forest.size(), C = forest.get(0).size();\n \n //1)\n for(int r = 0; r < R; r++){\n \n for(int c = 0; c < C; c++){\n \n int treeHeight = forest.get(r).get(c);\n \n if(treeHeight < 2) continue;\n \n trees.add(new int[]{ r, c, treeHeight});\n }\n }\n \n //2)\n Collections.sort(trees, (tree1, tree2) -> { return tree1[2] - tree2[2]; });\n \n int steps = 0;\n \n //3)\n int[] startTree = new int[] { 0, 0 };\n \n for(int[] nextTree : trees){\n \n int stepsToNextTree = getStepsToNextTree(forest, startTree, nextTree, R, C);\n \n //we could not make it to the next tree, therefore not all trees can be cut down\n if(stepsToNextTree < 0) return -1;\n \n steps += stepsToNextTree;\n \n //the current next tree becomes the new start tree\n \n startTree = nextTree;\n }\n \n return steps;\n }\n \n private int[][] directions = new int[][]{ {0, 1}, {0, -1}, {-1, 0}, {1, 0} };\n \n private int getStepsToNextTree(List<List<Integer>> forest, int[] startTree, int[] nextTree, int R, int C){\n \n //implelent bfs to move around the board taking steps to reach the next tree\n //do not move back to a visited tree within this function\n boolean[][] seen = new boolean[R][C];\n \n seen[startTree[0]][startTree[1]] = true;\n \n Queue<int[]> toVisit = new LinkedList<>();\n\n toVisit.offer(startTree);\n \n int steps = 0;\n \n while(!toVisit.isEmpty()){\n \n //pop elements off the q and process level by level\n int size = toVisit.size();\n \n for(int i = 0; i < size; i++){\n \n int[] visitedTree = toVisit.poll();\n \n //if we have reached the next tree we can stop\n if(visitedTree[0] == nextTree[0] && visitedTree[1] == nextTree[1]) return steps;\n\n //search surrounding cells for a connection to the next tree\n \n for(int[] dir : directions){\n \n int r = visitedTree[0] + dir[0];\n int c = visitedTree[1] + dir[1];\n \n if(r < R && c < C && r >= 0 && c >= 0 && !seen[r][c] && forest.get(r).get(c) > 0){\n \n toVisit.offer(new int[]{r, c});\n seen[r][c] = true;\n }\n }\n }\n \n //each time we visit a tree, we find all surrounding connected trees - however we only move one step when we visit that tree\n steps++;\n }\n \n //if we have proccessed all surrounding cells as possible but not found the nextTree that means we will cannot connect to it\n return -1;\n }\n}\n```
2
0
[]
1
cut-off-trees-for-golf-event
Ruby Accepted Solution
ruby-accepted-solution-by-gud-zdp3
I had few runs of here-and-there small optimizations which finally brought me to the AC Solution.\n\nThe main idea is: check all the skip cases for the cell bef
gud
NORMAL
2020-10-02T11:06:31.447625+00:00
2020-10-02T11:06:31.447658+00:00
85
false
I had few runs of here-and-there small optimizations which finally brought me to the AC Solution.\n\nThe main idea is: check all the skip cases for the cell before adding it to the queue.\n\n```\ndef cut_off_tree(forest)\n h = []\n\n for i in 0..forest.size - 1\n for j in 0..forest[0].size - 1\n if forest[i][j] > 1\n h.push(forest[i][j])\n end\n end\n end\n\n h.sort!\n\n helper(forest, 0, 0, h, 0)\nend\n\ndef helper(forest, istart, jstart, h, n)\n return if n == h.size\n target = h[n]\n q = [[istart, jstart]]\n\n step = 0\n visited = Array.new(forest.size) { Array.new(forest[0].size, 0) }\n while !q.empty?\n q.size.times do\n i, j = q.shift\n\n if forest[i][j] == target\n forest[i][j] = 1\n next_search = helper(forest, i, j, h, n + 1)\n return -1 if next_search == -1\n return step + next_search.to_i\n else\n if i - 1 >= 0 && forest[i - 1][j] > 0 && visited[i - 1][j] == 0\n q.push([i - 1, j])\n visited[i - 1][j] = 1\n end\n if i + 1 < forest.size && forest[i + 1][j] > 0 && visited[i + 1][j] == 0\n q.push([i + 1, j])\n visited[i + 1][j] = 1\n end\n if j - 1 >= 0 && forest[i][j - 1] > 0 && visited[i][j - 1] == 0\n q.push([i, j - 1])\n visited[i][j - 1] = 1\n end\n if j + 1 < forest[0].size && forest[i][j + 1] > 0 && visited[i][j + 1] == 0\n q.push([i, j + 1])\n visited[i][j + 1] = 1\n end\n end\n end\n\n step += 1\n end\n\n -1\nend
2
0
[]
0
cut-off-trees-for-golf-event
Python BFS solution, not TLE.
python-bfs-solution-not-tle-by-jason0323-ppyw
Python solution, not TLE\n\n\nclass Solution(object):\n def cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: in
jason0323
NORMAL
2020-09-16T04:59:19.496973+00:00
2020-09-21T04:14:18.233188+00:00
540
false
Python solution, not TLE\n\n```\nclass Solution(object):\n def cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: int\n """\n \n def bfs(sx, sy, tx, ty, target, forest):\n \n q = collections.deque([(sx, sy)])\n step = 0\n saved = set()\n saved.add((sx, sy))\n \n while q:\n l = len(q)\n for _ in range(l):\n cur = q.popleft()\n if cur == (tx, ty):\n return step\n dir = [(0,1), (0,-1),(1,0),(-1,0)]\n \n for dx, dy in dir:\n nx = cur[0] + dx\n ny = cur[1] + dy\n if nx < 0 or ny < 0 or nx >= len(forest) or ny >= len(forest[0]) or forest[nx][ny] == 0 or (nx, ny) in saved:\n continue\n saved.add((nx,ny))\n q.append((nx,ny))\n step+=1\n \n return -1\n \n \n \n m = len(forest[0])\n n = len(forest)\n tree = []\n \n for i in range(n):\n for j in range(m):\n if forest[i][j] > 1:\n tree.append((forest[i][j], i, j))\n \n tree.sort()\n sx = 0\n sy = 0\n ans = 0\n \n for t in tree:\n tx = t[1]\n ty = t[2]\n target = t[0]\n \n re = bfs(sx, sy, tx, ty, target, forest)\n if re == -1:\n return -1\n ans += re\n \n sx, sy = tx, ty\n return ans\n```
2
1
['Breadth-First Search', 'Python3']
1
cut-off-trees-for-golf-event
C++ with Priority Queue and BFS
c-with-priority-queue-and-bfs-by-rafatbi-di3g
put the tree positions into a set(remeber no two trees can have the same height?). this set will act as a priority queue.\n2. iterate the set and at every posit
rafatbiin
NORMAL
2020-07-14T06:01:39.938370+00:00
2020-07-14T06:03:17.727824+00:00
765
false
1. put the tree positions into a set(remeber no two trees can have the **same** height?). this set will act as a priority queue.\n2. iterate the set and at every position run a BFS, placing the tree position as the destination.\n\t1. if the BFS returns -1, there is no way we can cut off all the trees. return -1.\n\t2. else add the distnace to the answer.\n\nhere is the code:\n```\nclass Solution {\nprivate:\n const int INF = 1061109567;\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int n = forest.size() ;\n int m = forest[0].size() ;\n \n int ans = 0 ;\n \n set<pair<int,pair<int,int>>> points ;\n \n for(int i = 0; i<n ; i++){\n for(int j = 0; j<m; j++){\n if(forest[i][j]>1){\n points.insert({forest[i][j], {i,j}}) ;\n }\n }\n }\n\t\t\n int sx = 0, sy = 0 ;\n for(auto elem :points){\n int dx = elem.second.first ;\n int dy = elem.second.second ;\n int bfs_dist = bfs(forest, n, m, sx, sy, dx, dy) ;\n if(bfs_dist == -1) return -1 ;\n ans+=bfs_dist ;\n forest[dx][dy] = 1;\n sx = dx ;\n sy = dy ; \n }\n\t\t\n return ans ; \n }\n \n int bfs(vector<vector<int>> &forest, int n, int m , int sx, int sy, int dx, int dy){\n int distance[n+2][m+2] ;\n memset(distance, 0x3f, sizeof(distance));\n int dirx[] = {1, 0, -1, 0} ;\n int diry[] = {0, 1,0, -1} ;\n \n queue<pair<int,int>> q;\n q.push({sx,sy}) ;\n distance[sx][sy] = 0 ;\n \n while(!q.empty()){\n pair<int,int> p = q.front() ;\n q.pop() ;\n if(p.first == dx && p.second == dy) return distance[dx][dy] ;\n \n for(int i = 0 ;i<4 ;i++){\n int x = p.first + dirx[i] ;\n int y = p.second + diry[i] ;\n \n if(x<0 || x>=n || y <0 || y>=m)continue ;\n if(forest[x][y] == 0)continue ;\n if(distance[x][y] != INF)continue ;\n distance[x][y] = distance[p.first][p.second] + 1 ;\n q.push({x,y}) ;\n } \n \n }\n \n return -1 ; \n } \n};\n```
2
0
['Breadth-First Search', 'Heap (Priority Queue)', 'C++']
1
cut-off-trees-for-golf-event
Simple C# Solution (BFS + Sort)
simple-c-solution-bfs-sort-by-maxpushkar-of0d
\n public class Solution\n {\n private static readonly (int di, int dj)[] _directions = { (0, 1), (0, -1), (1, 0), (-1, 0) };\n\n private vo
maxpushkarev
NORMAL
2020-03-20T12:22:43.707615+00:00
2020-03-20T12:22:43.707649+00:00
324
false
```\n public class Solution\n {\n private static readonly (int di, int dj)[] _directions = { (0, 1), (0, -1), (1, 0), (-1, 0) };\n\n private void Helper((int i, int j) cellFrom, (int i, int j) cellTo, IList<IList<int>> forest, out int dist)\n {\n int n = forest.Count;\n int m = forest[0].Count;\n ISet<(int i, int j)> visited = new HashSet<(int i, int j)>();\n Queue<(int i, int j)> bfs = new Queue<(int i, int j)>();\n bfs.Enqueue(cellFrom);\n visited.Add(cellFrom);\n\n dist = 0;\n\n while (bfs.Count > 0)\n {\n int count = bfs.Count;\n for (int i = 0; i < count; i++)\n {\n var node = bfs.Dequeue();\n\n if (node.i == cellTo.i && node.j == cellTo.j)\n {\n return;\n }\n\n foreach (var dir in _directions)\n {\n int newI = node.i + dir.di;\n int newJ = node.j + dir.dj;\n\n if (newI >= 0 && newI < n && newJ >= 0 && newJ < m && forest[newI][newJ] != 0)\n {\n if(visited.Add((newI, newJ)))\n {\n bfs.Enqueue((newI, newJ));\n }\n }\n }\n }\n\n dist++;\n }\n\n dist = -1;\n }\n\n public int CutOffTree(IList<IList<int>> forest)\n {\n int n = forest.Count;\n if (n == 0)\n {\n return 0;\n }\n\n int m = forest[0].Count;\n\n\n List<(int i, int j, int h)> trees = new List<(int i, int j, int h)>();\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n if(forest[i][j] != 0)\n {\n trees.Add((i,j,forest[i][j]));\n }\n }\n }\n\n trees.Sort((d1, d2) => d1.h.CompareTo(d2.h));\n int res = 0;\n (int i, int j) currCell = (0, 0);\n\n for (int i = 0; i < trees.Count; i++)\n {\n Helper(currCell, (trees[i].i, trees[i].j), forest, out int dst);\n if (dst == -1)\n {\n return -1;\n }\n\n res += dst;\n currCell = (trees[i].i, trees[i].j);\n }\n\n return res;\n }\n }\n```
2
0
['Breadth-First Search']
1
cut-off-trees-for-golf-event
python solution sort + bfs O(n ** 2)
python-solution-sort-bfs-on-2-by-horizon-8tdq
```\nclass Solution(object):\n def cutOffTree(self, forest):\n row, col = len(forest), len(forest[0]) \n def bfs(i,j, target):\n que
horizon1006
NORMAL
2019-01-20T12:44:55.937675+00:00
2019-01-20T12:44:55.937718+00:00
393
false
```\nclass Solution(object):\n def cutOffTree(self, forest):\n row, col = len(forest), len(forest[0]) \n def bfs(i,j, target):\n queue = [(i,j, 0)] \n move = 0 \n s = {(i,j)}\n while queue:\n i,j, move = queue.pop(0) \n if forest[i][j] == target:\n return move \n for x,y in (i+1,j),(i,j+1),(i,j-1),(i-1,j):\n if 0 <= x < row and 0 <= y < col and (x,y) not in s:\n if forest[x][y]:\n queue.append((x,y,move+1)) \n s.add((x,y))\n return -1 \n g = sorted((forest[i][j],i,j) for i in range(row) for j in range(col) if forest[i][j] > 1)\n ans = 0\n x = y = 0\n while g:\n h,i,j = g.pop(0)\n move = bfs(x,y, h) \n if move == -1:\n return -1 \n ans += move \n x,y = i,j \n return ans\n
2
0
[]
0
cut-off-trees-for-golf-event
Java BFS ---- Easy to understand
java-bfs-easy-to-understand-by-meow1212m-lnd3
\nclass Solution {\n int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};\n public int cutOffTree(List<List<Integer>> forest) {\n //create a list
meow1212meow
NORMAL
2018-12-11T08:18:35.860019+00:00
2018-12-11T08:18:35.860063+00:00
541
false
```\nclass Solution {\n int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};\n public int cutOffTree(List<List<Integer>> forest) {\n //create a list of int[] {value, x, y}\n List<int[]> trees = new ArrayList<>();\n for (int i = 0; i < forest.size(); i++) {\n for (int j = 0; j < forest.get(0).size(); j++) {\n int value = forest.get(i).get(j);\n if (value > 1) trees.add(new int[]{i, j, value});\n }\n }\n \n Collections.sort(trees, (a, b)->(a[2]-b[2]));\n int res = 0, x = 0, y = 0;\n for (int[] tree: trees) {\n int dist = bfs(forest, x, y, tree[0], tree[1]);\n if (dist < 0) return -1;\n else {\n res += dist;\n x = tree[0];\n y = tree[1];\n }\n }\n return res;\n }\n private int bfs(List<List<Integer>> forest, int x, int y, int tx, int ty) {\n int m = forest.size(), n = forest.get(0).size();\n Queue<int[]> queue = new LinkedList<>();\n queue.add(new int[]{x, y});\n boolean[][] visited = new boolean[m][n];\n visited[x][y] = true;\n int dist = 0;\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int j = 0; j < size; j++) {\n int[] cur = queue.poll();\n if (cur[0] == tx && cur[1] == ty) return dist;\n for (int i = 0; i < 4; i++) {\n int nx = cur[0]+dirs[i][0];\n int ny = cur[1]+dirs[i][1];\n if (nx < 0 || nx >= m || ny < 0 || ny >= n || \n visited[nx][ny] || forest.get(nx).get(ny) <= 0) continue;\n visited[nx][ny] = true;\n queue.add(new int[]{nx, ny});\n }\n }\n dist++;\n }\n return -1;\n }\n}\n```
2
0
[]
0
cut-off-trees-for-golf-event
Swift solution - BFS
swift-solution-bfs-by-cl0ud_runner-1lg7
\nclass Solution {\n \n let directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n \n func cutOffTree(_ forest: [[Int]]) -> Int {\n if forest.coun
cl0ud_runner
NORMAL
2017-09-10T13:38:13.228000+00:00
2017-09-10T13:38:13.228000+00:00
379
false
```\nclass Solution {\n \n let directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n \n func cutOffTree(_ forest: [[Int]]) -> Int {\n if forest.count == 0 || forest[0].count == 0 {\n return -1\n }\n \n let m = forest.count\n let n = forest[0].count\n var result = 0\n var startX = 0\n var startY = 0\n var heights = [(Int, (Int, Int))]()\n \n for i in 0..<m {\n for j in 0..<n {\n if forest[i][j] > 1 {\n heights .append((forest[i][j], (i, j)))\n }\n }\n }\n heights.sort { (height1: (Int, (Int, Int)), height2: (Int, (Int, Int))) -> Bool in\n return height1.0 < height2.0\n }\n \n for i in 0..<heights.count {\n let endX = heights[i].1.0\n let endY = heights[i].1.1\n let steps = BFS(forest, m, n, startX, startY, endX, endY)\n if steps == -1 {\n return -1\n }\n result += steps\n startX = endX\n startY = endY\n }\n \n return result\n }\n \n private func BFS(_ forest: [[Int]], _ m: Int, _ n: Int, _ startX: Int, _ startY: Int, _ endX: Int, _ endY: Int) -> Int {\n if startX == endX && startY == endY {\n return 0\n }\n \n var steps = 0\n var queue = [(Int, Int)]()\n var visited = [[Bool]](repeatElement([Bool](repeatElement(false, count: n)), count: m))\n \n queue.append((startX, startY))\n visited[startX][startY] = true\n \n while !queue.isEmpty {\n let count = queue.count\n steps += 1\n for _ in 0..<count {\n let (x, y) = queue.removeFirst()\n for i in 0..<directions.count {\n let nextX = x + directions[i].0\n let nextY = y + directions[i].1\n if nextX >= 0 && nextX < m && nextY >= 0 && nextY < n && forest[nextX][nextY] > 0 && !visited[nextX][nextY] {\n if nextX == endX && nextY == endY {\n return steps\n }\n visited[nextX][nextY] = true\n queue.append((nextX, nextY))\n }\n }\n }\n }\n \n return -1\n }\n \n}\n```
2
0
['Breadth-First Search', 'Swift']
0
cut-off-trees-for-golf-event
C++ BFS with optimization, 86ms beats 100%
c-bfs-with-optimization-86ms-beats-100-b-kg26
If you are going from (x1,y1) to (x2,y2), instead of doing 4-direction (up,down,left,right) BFS, we can first do 2-direction BFS to see if there exists a shorte
niwota
NORMAL
2017-09-10T17:42:03.478000+00:00
2017-09-10T17:42:03.478000+00:00
946
false
If you are going from (x1,y1) to (x2,y2), instead of doing 4-direction (up,down,left,right) BFS, we can first do 2-direction BFS to see if there exists a shortest path from source to destination.\n\ne.g. going from S(x1,y1) to T(x2,y2) we know we have to take lower-right direction, that is, either go right or down. ```'X'``` is obstacle, ```'*'``` is current layer, shortest length = 5, going step by step as follow:\n```\n[S, , , ] [ ,*, , ] [ , ,*, ] [ , , ,*] [ , , , ] [ , , , ]\n[ , ,X, ] -> [*, ,X, ] -> [ ,*,X, ] -> [ , ,X, ] -> [ , ,X,*] -> [ , ,X, ]\n[X, , ,T] [X, , ,T] [X, , , ] [X,*, , ] [X, ,*, ] [X, , ,*] \n```\nIf there is no shortest path available and have to make a detour, then we have to do conventional BFS.\ne.g.\n```\n[ ,X, , , ]\n[ ,S, ,X, ]\n[ , , ,X, ] \n[ , ,X, ,T] \n[X, , , , ] \n```\nThis is very efficient if obstacle is sparse in the forest.\n```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n vector<vector<int>> trees; //vector<[height,i,j]>\n for(int i=0; i<forest.size(); ++i)\n for(int j=0; j<forest[0].size(); ++j)\n if(forest[i][j]>1)\n trees.push_back(vector<int>({forest[i][j],i,j}));\n sort(trees.begin(),trees.end(),[](vector<int>& a, vector<int>& b){\n return a[0]<b[0]; //sort by tree's height\n });\n \n //doing DFS to see if every tree is available from (0,0)\n int tree_available = 0;\n vector<vector<bool>> visited(forest.size(),vector<bool>(forest[0].size(),false));\n DFS(0,0,visited,forest,tree_available);\n if(tree_available != trees.size()) return -1; //some trees are not available from (0,0)\n \n int step = 0;\n int si=0, sj=0;\n for(int i=0; i<trees.size(); ++i){\n // optimization here, if there are no obstacles blocking the shortest path, return the shortest length \n // no need to do the 4-direction BFS\n if(ShortestPathAvailable(si,sj,trees[i][1],trees[i][2],forest))\n step += abs(si-trees[i][1])+abs(sj-trees[i][2]);\n else\n step += BFS(si,sj,trees[i][1],trees[i][2],forest);\n si = trees[i][1];\n sj = trees[i][2];\n }\n \n return step;\n }\n \n void DFS(int i, int j, vector<vector<bool>>& visited, const vector<vector<int>>& forest, int& count){\n if(i<0 || i>=forest.size() || j<0 || j>=forest[0].size() || visited[i][j] || forest[i][j]==0) return;\n visited[i][j] = true;\n if(forest[i][j]>1) count++;\n DFS(i+1,j,visited,forest,count);\n DFS(i-1,j,visited,forest,count);\n DFS(i,j+1,visited,forest,count);\n DFS(i,j-1,visited,forest,count);\n }\n \n //return the minimum step from (si,sj) to (ti,tj)\n int BFS(int si, int sj, int ti, int tj, const vector<vector<int>>& forest){\n vector<vector<bool>> visited(forest.size(),vector<bool>(forest[0].size(),false));\n visited[si][sj] = true;\n queue<pair<int,int>> q({make_pair(si,sj)});\n int len = 0;\n int di[4] = {1,0,-1,0};\n int dj[4] = {0,1,0,-1};\n while(true){\n int qsize = q.size();\n while(qsize--){\n if(q.front().first==ti && q.front().second==tj) //the function stops here\n return len; \n for(int k=0; k<4; ++k){\n int i=q.front().first+di[k];\n int j=q.front().second+dj[k];\n if(i>=0 && i<forest.size() && j>=0 && j<forest[0].size() && !visited[i][j] && forest[i][j]>0){\n visited[i][j] = true;\n q.push(make_pair(i,j));\n }\n }\n q.pop();\n }\n ++len;\n }\n return -999999; //redundancy, never goes this line\n }\n \n // check if there exists a shortest path avail from (x1,y1) to (x2,y2) going one out of 4 directions :\n // upper-left , upper-right , lower-left , lower-right\n /* e.g. going from S(x1,y1) to T(x2,y2), 'X' is obstacle, '*' is current layer\n lower-right direction, minumum step = 5, going step by step as follow\n [S, , , ] [ ,*, , ] [ , ,*, ] [ , , ,*] [ , , , ] [ , , , ]\n [ , ,X, ] -> [*, ,X, ] -> [ ,*,X, ] -> [ , ,X, ] -> [ , ,X,*] -> [ , ,X, ]\n [X, , ,T] [X, , , ] [X, , , ] [X,*, , ] [X, ,*, ] [X, , ,*] \n step 1 step 2 step 3 step 4 step 5\n */\n bool ShortestPathAvailable(int x1, int y1, int x2, int y2, const vector<vector<int>>& forest){\n int dx = (x2>x1)? 1 : -1;\n int dy = (y2>y1)? 1 : -1;\n int minstep = abs(x1-x2)+abs(y1-y2);\n queue<pair<int,int>> q({make_pair(x1,y1)});\n while(minstep--){\n int qsize = q.size();\n if(qsize==0) \n return false; //haven't gone minstep yet, but no path available\n while(qsize--){\n int x = q.front().first;\n int y = q.front().second;\n q.pop();\n if(x!=x2 && forest[x+dx][y]>0 && ((x+dx)!=q.back().first || y!=q.back().second))\n q.push(make_pair(x+dx,y));\n if(y!=y2 && forest[x][y+dy]>0 && (x!=q.back().first || (y+dy)!=q.back().second))\n q.push(make_pair(x,y+dy));\n }\n }\n return q.size()==1; //if true return, only destination [x2,y2] is in the queue\n }\n};\n```
2
0
[]
1
cut-off-trees-for-golf-event
Easy to understand solution in C++ using BFS with Explanation.
easy-to-understand-solution-in-c-using-b-sb76
Intuition\n\n- Given a matrix with numbers.\n- 0 is forbidden\n- 1 is final state for all.\n- Other integers are trees which are to be cut down from smallest to
KshitijKarnawat
NORMAL
2024-08-25T04:45:39.893637+00:00
2024-08-25T04:46:46.073812+00:00
419
false
# Intuition\n\n- Given a matrix with numbers.\n- 0 is forbidden\n- 1 is final state for all.\n- Other integers are trees which are to be cut down from smallest to tallest (will need to sort)\n- Shortest path calculated using some path planning algorithm (BFS, DFS or A-star)\n\n# Approach\n\n### Forest Problem Approch\n\nIterate over the matrix and store all values greater than $1$ in a sorted manner as we are moving from smallest to tallest.\n\nAlso we need the location of the smallest tree as we will have to traverse to that location from our start point $(0,0)$. As we need a co-relation between location and tree size an ordered map is a good choice as it will sort it for us.\n\nWhile map is not empty get the smallest tree (i.e. `map.begin()`) and find the shortest path to this tree from our current position.\n\nCalculate the distance from current location to the tree using BFS and add it to the total distance travelled. If it is not reachable `return -1;` and exit from the program. \n\nRemove this tree from the map as we have cut it down once we reach it and update our current location.\n\n### BFS Approach\n\nCreate another matrix of the same size to keep a record of the visited nodes.\n\nCreate a queue and add current location to it. While qeueue is not empty find valid neighbours mark them as visited and push them to the queue. We store the size of the queue before finding the neighbours to record the distance as all the neighbours will have the same distance (Level Order Traversal).\n\nIncrement the distance once all the nodes in a level are visited. if the queue is not empty repeat the process. Check if the newly poped node is our destination. if yes return the distance, else continue.\n\nIf queue is empty and destination node hasn\'t been reached yet return -1 as it cannnot be reached.\n\n# Complexity\n\n### Time complexity\n \n1. Insertion of each element in map is $O(log(n))$ for $n \\times m$ trees it will take $O((n \\times m) \\cdot log(n))$.\n2. While loop execution + BFS $O((n \\times m)^2)$\n - While loop running till map is empty takes time $O(n \\times m)$ as there are a maximum of nxm trees.\n - BFS takes $O(n \\times m)$ as there are $n \\times m$ nodes to traverse.\n\nTotal Time Complexity $O((n \\times m)^2)$\n\n### Space complexity:\n1. Space required by map $O(n \\times m)$\n2. Space required by visited matrix $O(n \\times m)$\n3. Space required by queue in worst case $O(n \\times m)$\n\nTotal Space Complexity $O(n \\times m)$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n \n int cutOffTree(vector<vector<int>>& forest) {\n map<int, vector<int>> trees;\n\n // find location of all trees to cut\n for(int i = 0; i < forest.size(); i++){\n for(int j = 0; j<forest[0].size(); j++){\n if(forest[i][j] > 1) trees[forest[i][j]] = {i,j};\n }\n }\n \n int total_distance = 0;\n \n vector<int> current_location{0,0};\n //find path to smallest tree.\n while(!trees.empty()){\n // ordered map begins with smallest key\n vector<int> smallest_tree_location = trees.begin()->second; //get location of smallest tree\n trees.erase(trees.begin());\n int distance = bfs(forest, current_location, smallest_tree_location);\n if(distance < 0) return -1;\n total_distance += distance;\n current_location = smallest_tree_location;\n }\n \n return total_distance;\n }\n \n \n int bfs(vector<vector<int>>& grid, vector<int> start, vector<int>end){\n \n int rows = grid.size();\n int cols = grid[0].size();\n \n vector<vector<int>> visited(rows, vector<int>(cols, 0)); \n \n int distance = 0;\n \n queue<pair<int,int>> q;\n \n q.push(make_pair(start[0],start[1]));\n \n while(!q.empty()){\n int size = q.size();\n \n // Distance increments after each level\n while(size--){\n auto loc = q.front();\n q.pop();\n \n // Access pair contents using inbuilt methods first and second\n if(loc.first == end[0] && loc.second == end[1]) return distance;\n \n // move up\n if(loc.first != 0){\n if(grid[loc.first-1][loc.second] != 0 && visited[loc.first-1][loc.second] == 0){\n visited[loc.first-1][loc.second] = 1;\n q.push(make_pair(loc.first-1,loc.second));\n }\n }\n\n // move down\n if(loc.first != rows-1){\n if(grid[loc.first+1][loc.second] != 0 && visited[loc.first+1][loc.second] == 0){\n visited[loc.first+1][loc.second] = 1;\n q.push(make_pair(loc.first+1,loc.second));\n }\n }\n\n // move left\n if(loc.second != 0){\n if(grid[loc.first][loc.second-1] != 0 && visited[loc.first][loc.second-1] == 0){\n visited[loc.first][loc.second-1] = 1;\n q.push(make_pair(loc.first,loc.second-1));\n }\n }\n\n // move right\n if(loc.second != cols-1){\n if(grid[loc.first][loc.second+1] != 0 && visited[loc.first][loc.second+1] == 0){\n visited[loc.first][loc.second+1] = 1;\n q.push(make_pair(loc.first,loc.second+1));\n }\n }\n }\n distance++;\n }\n \n return -1;\n }\n};\n```
1
0
['Array', 'Breadth-First Search', 'Queue', 'Matrix', 'C++']
1
cut-off-trees-for-golf-event
Simple BFS - Go
simple-bfs-go-by-jaliph-ofmi
Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe idea is to find minimum steps between each consecutive numbers on the grid. \n\nA
jaliph
NORMAL
2024-06-22T12:42:43.531751+00:00
2024-06-22T12:42:43.531784+00:00
28
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe idea is to find minimum steps between each consecutive numbers on the grid. \n\nA simple BFS from 1 number to the very next number works. If such a path doesn\'t exist, return -1\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFind the consecutive numbers from the grid which are greater than 1s. \n\nSort the list to traverse on them based on their ordering.\n\nDo BFS on each pair, and count steps. add the steps to global sum.\n\nOn catch is how to handle the scenario that you always start from 0, 0 and the first entry in the list may not be 0, 0. To solve this. start from 0,0 by default and if such a 0, 0 already exist at start BFS will give 0. [BFS gives -1 if path not possible.]\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```\ntype Coord struct {\n\tx int\n\ty int\n\tval int\n}\n\nfunc cutOffTree(forest [][]int) int {\n\n\tR := len(forest)\n\tC := len(forest[0])\n\n\ttrees := []Coord{}\n\n\tfor i := range forest {\n\t\tfor j := range forest[i] {\n\t\t\tif forest[i][j] > 1 {\n\t\t\t\ttrees = append(trees, Coord{i, j, forest[i][j]})\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Slice(trees, func(i, j int) bool {\n\t\treturn trees[i].val < trees[j].val\n\t})\n\n\tpaths := [][]int{\n\t\t{1, 0},\n\t\t{0, 1},\n\t\t{0, -1},\n\t\t{-1, 0},\n\t}\n\n\tbfs := func(sx, sy, dx, dy int) int {\n\t\trow := R\n\t\tcol := C\n\t\tvisited := make([][]bool, row)\n\t\trows := make([]bool, row*col)\n\t\tfor i := range visited {\n\t\t\tvisited[i] = rows[i*C : (i+1)*C]\n\t\t}\n\n\t\tq := [][3]int{}\n\t\tq = append(q, [3]int{sx, sy, 0})\n\t\tvisited[sx][sy] = true\n\n\t\tfor len(q) > 0 {\n\t\t\tcurr := q[0]\n\t\t\tq = q[1:]\n\n\t\t\tif curr[0] == dx && curr[1] == dy {\n\t\t\t\treturn curr[2]\n\t\t\t}\n\n\t\t\tfor _, p := range paths {\n\t\t\t\tnx := p[0] + curr[0]\n\t\t\t\tny := p[1] + curr[1]\n\n\t\t\t\tif nx >= 0 && nx < R && ny >= 0 && ny < C && !visited[nx][ny] && forest[nx][ny] != 0 {\n\t\t\t\t\tvisited[nx][ny] = true\n\t\t\t\t\tq = append(q, [3]int{nx, ny, curr[2] + 1})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\tcount := 0\n\tstart := Coord{x: 0, y: 0}\n\tfor i := 0; i < len(trees); i++ {\n\t\tdist := bfs(start.x, start.y, trees[i].x, trees[i].y)\n\t\tif dist == -1 {\n\t\t\treturn -1\n\t\t}\n\t\tstart.x = trees[i].x\n\t\tstart.y = trees[i].y\n\t\tcount += dist\n\t}\n\treturn count\n}\n```
1
0
['Go']
1
cut-off-trees-for-golf-event
EASY BFS SOLUTION
easy-bfs-solution-by-prafullashekhar-8vr6
Intuition\nFirst of all, we will determine the order in which we have to cut the trees. Let\'s say that we have to cut the trees in the order [t3, t2, t4, t1].
prafullashekhar
NORMAL
2024-02-15T19:12:20.855368+00:00
2024-02-15T19:12:20.855391+00:00
129
false
# Intuition\nFirst of all, we will determine the order in which we have to cut the trees. Let\'s say that we have to cut the trees in the order [t3, t2, t4, t1]. We will start by going to t3 from (0,0), then proceed to cut t3. Afterward, we will move to t2 from t3, then to t4, and finally to t1.\n\n# Approach\nCreated a vector of tuples to sort in the desired way, then performed BFS to each target position from the current position.\n\n# Complexity\n- Time complexity:\n\n- Space complexity:\n\n# Code\n```\n#define mypair pair<int, pair<int, int>>\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int n = forest.size(), m = forest[0].size();\n vector<mypair> trees;\n for(int i=0; i<n; i++)\n for(int j=0; j<m; j++)\n if(forest[i][j] > 1) \n trees.push_back({forest[i][j], {i, j}});\n sort(trees.begin(), trees.end());\n /* \n created the order to cut the tree, \n so will find the distance to traver each of them one by one.\n */\n\n int steps = 0;\n int sx=0, sy=0;\n for(int i=0; i<trees.size(); i++){\n int ex = trees[i].second.first;\n int ey = trees[i].second.second;\n int req = minSteps(forest, sx, sy, ex, ey);\n if(req < 0) return -1;\n steps += req;\n sx = ex; \n sy = ey;\n }\n return steps;\n }\n\n // find the minimum steps to move from {sx, sy} to {ex, ey}\n int minSteps(vector<vector<int>>& forest, int sx, int sy, int ex, int ey){\n if(sx==ex && sy==ey)return 0;\n int n = forest.size(), m = forest[0].size();\n vector<vector<bool>> vis(n, vector<bool>(m, false));\n\n vector<int> dx = {-1, 0, 1, 0};\n vector<int> dy = {0, 1, 0, -1};\n\n queue<pair<int, pair<int, int>>> q;\n q.push({0, {sx, sy}});\n vis[sx][sy]=true;\n while(!q.empty()){\n mypair node = q.front();\n q.pop();\n sx = node.second.first; sy = node.second.second;\n for(int j=0; j<4; j++){\n int nx = sx + dx[j];\n int ny = sy + dy[j];\n if(checkValid(forest, nx, ny) ){\n if(!vis[nx][ny]){\n vis[nx][ny] = true;\n if(nx==ex && ny==ey){\n forest[nx][ny]=1;\n return node.first+1;\n }\n q.push({node.first+1, {nx, ny}});\n }\n }\n }\n }\n return -1;\n }\n\n bool checkValid(vector<vector<int>>& forest, int x, int y){\n int n = forest.size(), m = forest[0].size();\n if(x>=0 && x<n && y>=0 && y<m && forest[x][y] >= 1) return true;\n return false;\n }\n};\n```
1
0
['C++']
0
cut-off-trees-for-golf-event
Most Detailed Solution || Explained Approach || Sorting + BFS
most-detailed-solution-explained-approac-5o3x
Code\n\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n\n // Given : Clear the trees in increasing order of height\n
manraj_singh_16447
NORMAL
2023-09-13T19:09:48.651352+00:00
2023-09-13T19:09:48.651373+00:00
79
false
# Code\n```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n\n // Given : Clear the trees in increasing order of height\n // constraints : n , m <= 50 = Larger Complexity Acceptable\n\n // Solution : To handle the contriant we are given that we have to cut them\n // in increasing order which provides us with solution itself\n\n // If gives tress are [ 10 , 12 , 11 ]\n // if i cut 10 next i have to cut will be 11 and i need to find a way to reach 11 \n // if possible find steps to it if not return -1\n\n vector<vector<int>> trees;\n for(int i = 0; i < forest.size(); i++){\n\n for(int j = 0; j < forest[0].size(); j++){\n\n if(forest[i][j] > 1){\n\n trees.push_back({forest[i][j] , i , j});\n }\n }\n cout<<endl;\n }\n\n // sorting the trees according to their height\n sort(trees.begin() , trees.end());\n\n // how it gurantees minimum ? As bfs does a level order search so we will\n // surely get the closest step automatically\n\n // defining all valid moves in advance\n vector<pair<int,int>> moves = {{0 , 1} , {1 , 0} , { 0 , -1} , {-1 , 0}};\n\n // defining start points \n int sx = 0 , sy = 0;\n int ans = 0;\n // now we will cut trees in order\n for(int i = 0; i < trees.size(); i++){\n \n // using breadth first search to find if next tree is reachable or not\n int cost = bfs(forest , sx , sy , trees[i][1] , trees[i][2] , moves);\n // if not reachable return -1\n if(cost == -1){\n \n return -1;\n }\n // if reachable add the 1 to cost\n ans += cost;\n // update the start points to new tree\n sx = trees[i][1];\n sy = trees[i][2];\n\n }\n\n return ans;\n \n }\n\n int bfs(vector<vector<int>> forest , int sx , int sy , int fx , int fy , vector<pair<int,int>> &moves){\n\n // if we are search for start point\n if(fx == sx && fy == sy) return 0;\n\n // now let\'s do a bfs \n\n queue<pair<int,int>> q;\n q.push({sx , sy});\n int n = forest.size() , m = forest[0].size();\n vector<vector<int>> seen(n , vector<int>(m , 0));\n seen[sx][sy] = 1;\n int cost = 0;\n while(!q.empty()){\n\n int qsize = q.size();\n // iterating the current level\n for(int i = 0; i < qsize; i++){\n\n pair<int,int> point = q.front();\n q.pop();\n\n for(int j = 0 ; j < moves.size(); j++){\n\n long int newx = point.first + moves[j].first;\n long int newy = point.second + moves[j].second;\n\n // skip if new point is not valid point\n if(newx >= n || newy >= m || newx < 0 || newy < 0 ) continue;\n\n // if new point is not obstacle and also not seen before the add it\n if(forest[newx][newy] != 0 && seen[newx][newy] == 0){\n\n q.push({newx , newy});\n seen[newx][newy] = 1;\n\n if(newx == fx && newy == fy){\n\n return cost + 1;\n }\n\n }\n \n }\n \n }\n \n cost++;\n\n\n }\n\n // if not found return -1\n return -1;\n\n\n }\n};\n```
1
0
['Breadth-First Search', 'Sorting', 'C++']
0
cut-off-trees-for-golf-event
🚧Easy C++ Solution with Intuition and Approach || PQ + BFS
easy-c-solution-with-intuition-and-appro-9vtw
Intuition\nAs there are trees of different distinct heights and we have to cut them in ascending order of their heights , \n> Its for sure that if we have 4 tre
teqarine
NORMAL
2023-08-18T14:41:54.173246+00:00
2023-08-18T14:45:08.660603+00:00
63
false
# Intuition\nAs there are trees of different distinct heights and we have to cut them in ascending order of their heights , \n> Its for sure that if we have 4 trees with heights 1,2,3,4 at different positions in the forest , then we\'ll cut the trees in the order 1->2->3->4 ; \n\nThus, we first sort the heights of the trees using a min-heap pq , and then just sum the distances of moving from the min to the second min and so on until only one element is left in the pq.\n\n> (i..e.. dist 1->2 + dist 2->3 + dist 3->4) , then only one element in pq which is 4 , which is the max height tree of the forest....\n\n# Approach\n- First we store all the trees in a min-heap to attain their ascending sorted order.\n- Then, we just sum the consequent distances of moving from the min height tree to the second min height tree and so on until only one tree is left in the minheap(which is the max height tree, marking that we have cut all the trees now and don\'t need to continue any further).\n- We find these distances of moving from one point to the other using simple bfs\n- Dijikstra\'s algorithm can also be used in order to optimize time but as the constraints are not that strict a simple bfs works for us here.\n\n---\n> Do upvote if helpful , Happy Coding\uD83C\uDF86\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n int x[4]={0,0,1,-1};\n int y[4]={1,-1,0,0};\n\n int bfs(vector<vector<int>> &forest,int curri,int currj,int dsti,int dstj,int m,int n){\n int out=0;\n queue<pair<int,int>> q;\n vector<vector<bool>> vis(m,vector<bool>(n,false));\n q.push({curri,currj});\n vis[curri][currj]=true;\n int steps=0;\n\n while(!q.empty()){\n steps++;\n int size=q.size();\n while(size--){\n int i=q.front().first;\n int j=q.front().second;\n q.pop();\n if(i==dsti && j==dstj)return steps-1;\n for(int k=0;k<4;k++){\n int nr=i+x[k];\n int nc=j+y[k];\n if(nr>=0 && nr<m && nc>=0 && nc<n && !vis[nr][nc] && forest[nr][nc]!=0){\n if(nr==dsti && nc==dstj)return steps;\n q.push({nr,nc});\n vis[nr][nc]=true;\n }\n }\n }\n }\n\n return -1;\n }\n\n int cutOffTree(vector<vector<int>>& forest) {\n int m=forest.size();\n int n=forest[0].size();\n priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> pq;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(forest[i][j]>1)pq.push({forest[i][j],{i,j}});\n }\n }\n pq.push({1,{0,0}});\n int out=0;\n while(pq.size()>1){\n int curri=pq.top().second.first , currj=pq.top().second.second;\n pq.pop();\n int dsti=pq.top().second.first , dstj=pq.top().second.second;\n int temp=bfs(forest,curri,currj,dsti,dstj,m,n);\n if(temp==-1)return -1;\n out+=temp;\n }\n return out;\n }\n};\n```\n![upvote xd.jpeg](https://assets.leetcode.com/users/images/e5e8e93f-0df9-4835-b71a-2a9468920807_1692369668.9972389.jpeg)\n
1
0
['Breadth-First Search', 'Heap (Priority Queue)', 'C++']
0
cut-off-trees-for-golf-event
C++ Beats 100%
c-beats-100-by-antony_ft-fd22
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
antony_ft
NORMAL
2023-07-17T11:32:53.338613+00:00
2023-07-17T11:32:53.338632+00:00
39
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 static constexpr int DIR[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};\n struct Cell {\n short r : 8;\n short c : 8;\n };\n int doit(const vector<vector<int>>& forest, Cell start, vector<int> &curr, vector<int> &prev, vector<Cell> &bfs) {\n const int M = forest.size(), N = forest[0].size();\n int steps = 0;\n swap(curr, prev);\n fill(begin(curr), end(curr), -1);\n curr[start.r * N + start.c] = steps;\n if (prev[start.r * N + start.c] != -1) {\n return prev[start.r * N + start.c];\n }\n bfs.clear();\n bfs.push_back(start);\n while (!bfs.empty()) {\n int size = bfs.size();\n steps++;\n while (size--) {\n auto [r0, c0] = bfs[size];\n swap(bfs[size], bfs.back());\n bfs.pop_back();\n for (auto [dr, dc] : DIR) {\n short r1 = r0 + dr, c1 = c0 + dc;\n int pos = r1 * N + c1;\n if (r1 >= 0 && r1 < M && c1 >= 0 && c1 < N && forest[r1][c1] > 0 && curr[pos] == -1) {\n if (prev[pos] != -1) {\n return steps + prev[pos];\n }\n curr[pos] = steps;\n bfs.push_back({r1, c1});\n }\n }\n }\n }\n return -1;\n }\n int manhattan_distance(vector<Cell> &cells) {\n int result = 0;\n Cell prev{0, 0};\n for (auto &cell : cells) {\n result += abs(prev.r - cell.r) + abs(prev.c - cell.c);\n prev = cell;\n }\n return result;\n }\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n const int M = forest.size(), N = forest[0].size();\n if (forest[0][0] == 0) {\n return -1;\n }\n int obstacles = 0;\n vector<Cell> cells;\n cells.reserve(8);\n\n for (short r = 0; r < M; r++) {\n for (short c = 0; c < N; c++) {\n if (forest[r][c] > 1) {\n cells.push_back({r, c});\n } else if (forest[r][c] == 0) {\n obstacles++;\n }\n }\n }\n sort(begin(cells), end(cells), [&forest](const Cell &a, const Cell &b){\n return forest[a.r][a.c] < forest[b.r][b.c];\n });\n if (obstacles == 0) {\n return manhattan_distance(cells);\n }\n vector<int> curr(M * N, -1), prev = curr;\n curr[0] = 0;\n\n vector<Cell> bfs;\n bfs.reserve(8);\n\n int steps = 0;\n\n for (auto &cell : cells) {\n int result = doit(forest, cell, curr, prev, bfs);\n\n if (result != -1) {\n steps += result;\n } else {\n return -1;\n }\n }\n return steps;\n }\n};\n```
1
0
['C++']
0
cut-off-trees-for-golf-event
99.45 in speed
9945-in-speed-by-ranilmukesh-zslo
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
ranilmukesh
NORMAL
2023-05-31T15:20:04.446027+00:00
2023-05-31T15:20:04.446070+00:00
56
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 cutOffTree(self, forest: List[List[int]]) -> int:\n if forest[0][0] == 0 :\n return -1\n m = len(forest)\n n = len(forest[0])\n def distance(node1, node2):\n now = [node1]\n soon = []\n expanded = set()\n manhattan = abs(node1[0] - node2[0]) + abs(node1[1] - node2[1])\n detours = 0\n while True:\n if len(now) == 0:\n now = soon\n soon = []\n detours += 1\n node = now.pop()\n if node == node2:\n return manhattan + 2 * detours\n if node not in expanded:\n expanded.add(node)\n x, y = node\n if x - 1 >= 0 and forest[x - 1][y] >= 1:\n if x > node2[0]:\n now.append((x - 1, y))\n else:\n soon.append((x - 1, y))\n if y + 1 < n and forest[x][y + 1] >= 1:\n if y < node2[1]:\n now.append((x, y + 1))\n else:\n soon.append((x, y + 1))\n if x + 1 < m and forest[x + 1][y] >= 1:\n if x < node2[0]:\n now.append((x + 1, y))\n else:\n soon.append((x + 1, y))\n if y - 1 >= 0 and forest[x][y - 1] >= 1:\n if y > node2[1]:\n now.append((x, y - 1))\n else:\n soon.append((x, y - 1))\n trees = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n trees.append(((i, j), forest[i][j]))\n trees.sort(key=lambda x: x[1])\n can_reach = {(0, 0)}\n stack = [(0, 0)]\n while len(stack) > 0:\n x, y = stack.pop()\n if x - 1 >= 0 and forest[x - 1][y] >= 1 and (x - 1, y) not in can_reach:\n can_reach.add((x - 1, y))\n stack.append((x - 1, y))\n if y + 1 < n and forest[x][y + 1] >= 1 and (x, y + 1) not in can_reach:\n can_reach.add((x, y + 1))\n stack.append((x, y + 1))\n if x + 1 < m and forest[x + 1][y] >= 1 and (x + 1, y) not in can_reach:\n can_reach.add((x + 1, y))\n stack.append((x + 1, y))\n if y - 1 >= 0 and forest[x][y - 1] >= 1 and (x, y - 1) not in can_reach:\n can_reach.add((x, y - 1))\n stack.append((x, y - 1))\n for t in trees:\n if t[0] not in can_reach:\n return -1\n start = (0, 0)\n num_step = 0\n for t in trees: \n num_step += distance(start, t[0])\n forest[t[0][0]][t[0][1]] = 1\n start = t[0]\n return num_step\n```
1
0
['Python3']
0
cut-off-trees-for-golf-event
Java : using PriorityQueue and BFS
java-using-priorityqueue-and-bfs-by-abhi-isyd
Intuition\nUse PriorityQueue to store the tree positions heightwise in the increasing order. Use BFS to calculate distance between successive trees.\n\n# Approa
abhishekbalawan
NORMAL
2022-12-21T16:42:52.183000+00:00
2022-12-21T16:42:52.183048+00:00
63
false
# Intuition\nUse PriorityQueue to store the tree positions heightwise in the increasing order. Use BFS to calculate distance between successive trees.\n\n# Approach\nNotice that last constraint - Heights of all trees are distinct. So all the trees must be visited sequentially in increasing order of their heights. We store the position of the trees in PriorityQueue and use BFS to get minimum distance between two positions.\n\n# Complexity\n- Time complexity:\nIn the worst case, we are cutting m*n trees and for each time, we are fetching location data from PriorityQueue. So time complexity of this operation is (nm)log(nm). We are performing BFS for each tree with time complexity of O(nm). So, overall time complexity is ((nm)^2)log(nm).\n\n- Space complexity:\nO(nm) - for PriorotyQueue.\n\n# Code\n```\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>(\n (a,b) ->forest.get(a[0]).get(a[1]) - forest.get(b[0]).get(b[1])\n );\n for(int i=0; i<forest.size(); i++){\n for(int j=0; j<forest.get(0).size(); j++){\n if(forest.get(i).get(j) > 1){\n pq.add(new int[]{i, j});\n }\n }\n }\n \n int x = 0;\n int y = 0;\n int steps = 0;\n while(pq.isEmpty() == false){\n int[] nextPosition = pq.poll();\n int reqdStep = BFS(forest, x, y, nextPosition[0], nextPosition[1]);\n if(reqdStep >= 10000){\n return -1;\n }\n steps += reqdStep;\n x = nextPosition[0];\n y = nextPosition[1];\n }\n \n return steps;\n }\n \n int BFS(List<List<Integer>> forest, int x, int y, int newX, int newY){\n LinkedList<int[]> queue = new LinkedList<int[]>();\n int[][] dp = new int[forest.size()][forest.get(0).size()];\n for(int[] arr : dp){\n Arrays.fill(arr, 10000);\n }\n queue.addFirst(new int[]{x,y,0});\n while(queue.isEmpty() == false){\n int[] currentPosition = queue.removeLast();\n x = currentPosition[0];\n y = currentPosition[1];\n int countOfSteps = currentPosition[2];\n if(x<0 || x>=forest.size() || y<0 || y>=forest.get(0).size() || forest.get(x).get(y) == 0){\n continue;\n }\n if(dp[x][y] <= countOfSteps){\n continue;\n }\n dp[x][y] = countOfSteps;\n if(x == newX && y == newY){\n return dp[x][y];\n }\n queue.addFirst(new int[]{x-1, y, dp[x][y]+1});\n queue.addFirst(new int[]{x+1, y, dp[x][y]+1});\n queue.addFirst(new int[]{x, y-1, dp[x][y]+1});\n queue.addFirst(new int[]{x, y+1, dp[x][y]+1});\n }\n return 10000;\n }\n \n}\n```
1
0
['Breadth-First Search', 'Heap (Priority Queue)', 'Java']
0
cut-off-trees-for-golf-event
Just a runnable solution
just-a-runnable-solution-by-ssrlive-2rxj
Code\n\nimpl Solution {\n pub fn cut_off_tree(forest: Vec<Vec<i32>>) -> i32 {\n let mut trees = forest\n .iter()\n .enumerate()\
ssrlive
NORMAL
2022-12-07T04:02:51.040633+00:00
2022-12-07T04:02:51.040672+00:00
34
false
# Code\n```\nimpl Solution {\n pub fn cut_off_tree(forest: Vec<Vec<i32>>) -> i32 {\n let mut trees = forest\n .iter()\n .enumerate()\n .flat_map(|(i, row)| {\n row.iter()\n .enumerate()\n .filter_map(move |(j, &height)| if height > 1 { Some((height, i, j)) } else { None })\n })\n .collect::<Vec<_>>();\n trees.sort_unstable();\n\n let mut steps = 0;\n let mut start = (0, 0);\n for (_, i, j) in trees {\n let step = Self::bfs(&forest, start, (i, j));\n if step < 0 {\n return -1;\n }\n steps += step;\n start = (i, j);\n }\n steps\n }\n\n fn bfs(forest: &[Vec<i32>], start: (usize, usize), end: (usize, usize)) -> i32 {\n let mut queue = std::collections::VecDeque::new();\n queue.push_back((start, 0));\n let mut visited = std::collections::HashSet::new();\n visited.insert(start);\n\n while let Some(((i, j), step)) = queue.pop_front() {\n if (i, j) == end {\n return step;\n }\n\n for (di, dj) in &[(0, 1), (0, -1), (1, 0), (-1, 0)] {\n let (ni, nj) = (i as i32 + di, j as i32 + dj);\n if ni >= 0\n && ni < forest.len() as i32\n && nj >= 0\n && nj < forest[0].len() as i32\n && forest[ni as usize][nj as usize] > 0\n && visited.insert((ni as usize, nj as usize))\n {\n queue.push_back(((ni as usize, nj as usize), step + 1));\n }\n }\n }\n -1\n }\n}\n```
1
0
['Rust']
0
cut-off-trees-for-golf-event
Python 3 || improving BFS to avoid TLE
python-3-improving-bfs-to-avoid-tle-by-b-sp9k
Intuition\n Describe your first thoughts on how to solve this problem. \nBasically we sort the tree heights and get a sequence $(p_0,p_1,\ldots, p_k)$ of tree p
bangyewu
NORMAL
2022-11-27T01:57:10.198928+00:00
2022-11-27T02:01:30.195983+00:00
133
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasically we sort the tree heights and get a sequence $(p_0,p_1,\\ldots, p_k)$ of tree position, where $p_0=(0,0)$ is the starting position. Then, similar to most of the approaches, BFS is empolyed to find the distance between $p_i$ and $p_{i+1}$ for each $i$. However, this approach will suffer from TLE for Python coder. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe suggest a very simpe improvement for BFS. We can find the distance from one source to two destinations in one BFS. That is, we find the $distance(p_i, p_{i-1}) + distance(p_i, p_{i+1})$ in one BFS procedure. The number of BFS will be cut in half. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(mnk)$, where $k$ is the number of trees. The complexity in Big-O is the same, but running time is one half.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(mn)$, the same.\n# Code\n```\nclass Solution:\n # BFS search from i to i-1 and i+1\n def cutOffTree(self, forest: List[List[int]]) -> int:\n forest = [[0]*len(forest[0])] + forest \n # sentinel to save index check\n forest.append([0]*len(forest[0]))\n for i in range(len(forest)):\n forest[i] = [0]+forest[i]+[0]\n seq = [(0,1,1)] # starting point\n D0 = dict()\n for i,row in enumerate(forest):\n for j,x in enumerate(row):\n if x>1: seq.append((x,i,j))\n elif x==0: D0[(i,j)]=-1\n seq.sort() # sort the tree height\n def bfs(p0,p1,p2): # distance (p0,p1)+(p0,p2)\n #print(p0,p1,p2)\n que=[p0]; head=0 # FIFO queue\n D = D0.copy() # all 0 visited\n D[p0] = 0\n while head<len(que) and (p1 not in D or p2 not in D):\n r,c = que[head]; head += 1\n nd = D[(r,c)]+1\n for nr,nc in ((r-1,c),(r+1,c),(r,c-1),(r,c+1)):\n if (nr,nc) not in D:\n D[(nr,nc)] = nd\n que.append((nr,nc))\n #end for\n #endwhile\n if p1 not in D or p2 not in D:\n return -1\n return D[p1]+D[p2]\n #end BFS\n total = 0\n while len(seq)>2:\n # find dustance for last 3 points\n step = bfs(seq[-2][1:],seq[-1][1:],seq[-3][1:])\n if step<0: return -1\n total += step\n seq.pop(); seq.pop()\n if len(seq)>1: # when only two points left\n step = bfs(seq[0][1:],seq[0][1:],seq[1][1:])\n if step<0: return -1\n total += step\n return total\n\n\n```
1
0
['Python3']
0
cut-off-trees-for-golf-event
C# A* Solution
c-a-solution-by-infraredshift-8ivy
Intuition\nCouldn\'t find a C# A implementation, so decided to make one myself\n\n# Approach\nPriority Queue to find target nodes\nThen A search for pathfinding
infraredshift
NORMAL
2022-11-11T03:46:19.284168+00:00
2022-11-11T03:46:19.284212+00:00
102
false
# Intuition\nCouldn\'t find a C# A* implementation, so decided to make one myself\n\n# Approach\nPriority Queue to find target nodes\nThen A* search for pathfinding.\n\n\n# Code\n```\npublic class Solution {\n int ROWS;\n int COLS;\n IList<IList<int>> Forest;\n public int CutOffTree(IList<IList<int>> forest)\n {\n ROWS = forest.Count;\n COLS = forest[0].Count;\n Forest = forest;\n if (Forest[0][0] == 0)\n {\n return -1;\n }\n PriorityQueue<(int, int), int> pQue = new();\n pQue.Enqueue((0, 0), 0);\n for (int i = 0; i < ROWS; ++i)\n {\n for (int j = 0; j < COLS; ++j)\n {\n var current = forest[i][j];\n if (current > 1)\n {\n pQue.Enqueue((i, j), current);\n }\n }\n }\n\n if (pQue.Count < 2)\n {\n return 0;\n }\n var answer = 0;\n var currentStep = pQue.Dequeue();\n\n while (pQue.Count > 0)\n {\n var next = pQue.Dequeue();\n var nextSteps = BFSPath(currentStep, next);\n if (nextSteps == -1)\n {\n return -1;\n }\n answer += nextSteps;\n currentStep = next;\n }\n\n return answer;\n }\n\n int BFSPath((int, int) start, (int, int) end)\n {\n Dictionary<int,int> costs = new();\n PriorityQueue<MapNode,int> pQue = new();\n (var endR, var endC) = end;\n (var sr, var sc) = start;\n var steps = -1;\n var fNode = new MapNode(sr, sc, 0);\n pQue.Enqueue(fNode, 0);\n costs[fNode.r * COLS + fNode.c] = 0;\n while (pQue.Count > 0)\n {\n var node = pQue.Dequeue();\n if (node.r == endR && node.c == endC)\n {\n steps = node.depth;\n break;\n }\n var nextNodes = new[] { (node.r + 1, node.c), (node.r - 1, node.c), (node.r, node.c + 1), (node.r, node.c - 1) };\n foreach ((var r, var c) in nextNodes)\n {\n if (r >= 0 && r < ROWS && c >= 0 && c < COLS && Forest[r][c] != 0)\n {\n var h = Heuristic(r, c, endR, endC);\n var cost = node.depth + 1 + h;\n if(costs.TryGetValue(r * COLS + c, out var pcost) && pcost <= cost){\n continue;\n }\n pQue.Enqueue(new MapNode(r, c, node.depth + 1), cost);\n costs[r * COLS + c] = cost;\n }\n }\n }\n return steps;\n }\n \n int Heuristic(int r, int c, int er, int ec){\n return Math.Abs(r - er) + Math.Abs(c - ec);\n }\n\n class MapNode\n {\n public int r;\n public int c;\n public int depth;\n\n public MapNode(int R, int C, int Depth)\n {\n r = R;\n c = C;\n depth = Depth;\n }\n\n public override int GetHashCode()\n {\n return HashCode.Combine(r, c);\n }\n }\n}\n```
1
0
['C#']
0
cut-off-trees-for-golf-event
python: hadlock's algorithm, time complexity O((m*n)^2)
python-hadlocks-algorithm-time-complexit-b9y0
```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n def dist(forest, sr, sc, tr, tc):\n processed = set()\n
zoey513
NORMAL
2022-08-07T15:04:17.003183+00:00
2022-08-07T15:04:17.003230+00:00
128
false
```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n def dist(forest, sr, sc, tr, tc):\n processed = set()\n deque = collections.deque([(0, sr, sc)])\n while deque:\n detours, r, c = deque.popleft()\n if (r, c) not in processed:\n processed.add((r, c))\n if r == tr and c == tc:\n return abs(sr-tr) + abs(sc-tc) + 2*detours\n for nr, nc, closer in ((r-1, c, r > tr), (r+1, c, r < tr),\n (r, c-1, c > tc), (r, c+1, c < tc)):\n if 0 <= nr < m and 0 <= nc < n and forest[nr][nc]:\n if closer:\n deque.appendleft((detours, nr, nc))\n else:\n deque.append((detours+1, nr, nc))\n return -1\n trees = []\n m,n = len(forest),len(forest[0])\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n trees.append([forest[i][j],i,j])\n trees = sorted(trees)\n \n sr = sc = ans = 0\n for _, tr, tc in trees:\n d = dist(forest, sr, sc, tr, tc)\n if d < 0: return -1\n ans += d\n sr, sc = tr, tc\n return ans
1
0
[]
0
cut-off-trees-for-golf-event
Modern C# code solution, MinHeap + BFS
modern-c-code-solution-minheap-bfs-by-us-iuog
\npublic class Solution {\n public int CutOffTree(IList<IList<int>> forest) {\n \n // The main idea is that we will put all the trees in minHea
user1189c
NORMAL
2022-07-16T00:16:05.622267+00:00
2022-07-16T00:16:42.102257+00:00
69
false
```\npublic class Solution {\n public int CutOffTree(IList<IList<int>> forest) {\n \n // The main idea is that we will put all the trees in minHeap in order to\n // cut them from lower height to higher.\n // Then, to find out distance between two adjacent trees we\'ll use BFS\n const int BLOCK = 0;\n \n var directions = new (int dR, int dC)[] { (-1, 0), (0, 1), (1, 0), (0, -1) };\n \n int rows = forest.Count;\n int columns = forest[0].Count;\n \n PriorityQueue<(int row, int column), int> minHeap = new();\n \n for (int row = 0; row < rows; row++)\n for (int column = 0; column < columns; column++)\n {\n int height = forest[row][column];\n \n if (height > 1) minHeap.Enqueue((row, column), height);\n }\n \n int totalSteps = 0;\n (int row, int column) source = (0, 0);\n \n while (minHeap.TryDequeue(out var target, out _))\n {\n int stepsTaken = minSteps(source.row, source.column, target.row, target.column);\n \n if (stepsTaken == -1) return -1;\n \n totalSteps += stepsTaken;\n \n source = target;\n }\n \n return totalSteps;\n \n int minSteps(int sourceRow, int sourceColumn, int targetRow, int targetColumn)\n {\n HashSet<(int, int)> visited = new();\n Queue<(int, int)> queue = new();\n \n queue.Enqueue((sourceRow, sourceColumn));\n \n int steps = 0;\n \n while (queue.Count > 0)\n {\n int layerLength = queue.Count;\n \n for (int i = 0; i < layerLength; i++)\n {\n (int row, int column) = queue.Dequeue();\n \n if (row == targetRow && column == targetColumn) return steps;\n \n foreach (var direction in directions)\n {\n int nextRow = row + direction.dR;\n int nextColumn = column + direction.dC;\n \n if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || \n nextColumn >= columns || forest[nextRow][nextColumn] == BLOCK) continue;\n \n if (visited.Contains((nextRow, nextColumn))) continue;\n \n visited.Add((nextRow, nextColumn));\n queue.Enqueue((nextRow, nextColumn));\n }\n }\n \n steps++;\n }\n \n return -1; \n } \n }\n}\n```
1
0
[]
0
cut-off-trees-for-golf-event
Python Solution [Simplest] NOT TLE (BFS + Graph)
python-solution-simplest-not-tle-bfs-gra-ijg9
\nimport collections\nfrom functools import reduce\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n graph = collections.defa
guigui309
NORMAL
2022-07-14T20:11:10.351349+00:00
2022-07-14T20:12:03.283046+00:00
227
false
```\nimport collections\nfrom functools import reduce\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n graph = collections.defaultdict(list)\n m = len(forest)\n n = len(forest[0])\n for i in range(m):\n for j in range(n):\n if forest[i][j] != 0:\n north = forest[i-1][j] if i-1 >= 0 and forest[i-1][j] != 0 else None\n east = forest[i][j+1] if j+1 < n and forest[i][j+1] != 0 else None\n south = forest[i+1][j] if i+1 < m and forest[i+1][j] != 0 else None\n west = forest[i][j-1] if j-1 >= 0 and forest[i][j-1] != 0 else None\n graph[forest[i][j]] = list(filter(lambda x: x != None,[north,east,south,west]))\n trees = []\n for i in forest: trees.extend(filter(lambda x: x != 0 and x!= 1, i))\n trees.sort()\n moves = 0\n initial_point = forest[0][0]\n for i in trees:\n tmp_move = self.min_dist(initial_point,i,graph)\n if tmp_move == None:\n return -1\n moves += tmp_move\n initial_point = i\n return moves\n \n def min_dist(self,begin:int,target:int,graph:dict[int,list]) -> int:\n visited = set()\n stack = collections.deque([])\n visited.add(begin)\n distance = {}\n for d in graph.keys() : distance[d] = None\n distance[begin] = 0\n stack.append(begin)\n while len(stack) > 0:\n t = stack.popleft()\n if t == target:\n return distance[t]\n for i in graph[t]:\n if i not in visited:\n visited.add(i)\n stack.append(i)\n distance[i] = distance[t] + 1\n \n \n```
1
0
[]
0
cut-off-trees-for-golf-event
BFS +heights of trees in sorted order
bfs-heights-of-trees-in-sorted-order-by-rpgdb
\tclass Solution:\n\t\tdef bfs(self,v,i,j,n,m,forest):\n\t\t\tvis=set([i,j])\n\t\t\tq=deque([[i,j,0]])\n\t\t\twhile q:\n\t\t\t\tx,y,d=q.pop()\n\t\t\t\tif forest
gabhay
NORMAL
2022-07-02T16:13:47.171867+00:00
2022-07-16T05:37:06.895742+00:00
260
false
\tclass Solution:\n\t\tdef bfs(self,v,i,j,n,m,forest):\n\t\t\tvis=set([i,j])\n\t\t\tq=deque([[i,j,0]])\n\t\t\twhile q:\n\t\t\t\tx,y,d=q.pop()\n\t\t\t\tif forest[x][y]==v:\n\t\t\t\t\treturn x,y,d\n\t\t\t\tfor i,j in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:\n\t\t\t\t\tif 0<=i<n and 0<=j<m and not (i,j) in vis and forest[i][j]:\n\t\t\t\t\t\tvis.add((i,j))\n\t\t\t\t\t\tq.appendleft([i,j,d+1])\n\t\t\treturn -1,-1,-1\n\n\t\tdef cutOffTree(self, forest: List[List[int]]) -> int:\n\t\t\torder=[]\n\t\t\tn,m=len(forest),len(forest[0])\n\t\t\tfor i in range(n):\n\t\t\t\tfor j in range(m):\n\t\t\t\t\tif forest[i][j]>1:\n\t\t\t\t\t\torder.append(forest[i][j])\n\t\t\torder.sort()\n\t\t\tres,x,y=0,0,0\n\t\t\tfor num in order:\n\t\t\t\tx,y,d=self.bfs(num,x,y,n,m,forest)\n\t\t\t\tif d==-1:\n\t\t\t\t\treturn -1\n\t\t\t\telse:\n\t\t\t\t\tres+=d\n\t\t\treturn res\n
1
0
['Breadth-First Search', 'Sorting']
0
cut-off-trees-for-golf-event
[C++] | Simple BFS
c-simple-bfs-by-decifend_contest-jyz8
\nclass Solution {\npublic:\n map<int, int> hash;\n vector<int> DIR = {1, 0, -1, 0, 1};\n int n, m;\n int cutOffTree(vector<vector<int>>& f) {\n
Decifend_contest
NORMAL
2022-06-30T20:07:04.421180+00:00
2022-06-30T20:07:04.421221+00:00
826
false
```\nclass Solution {\npublic:\n map<int, int> hash;\n vector<int> DIR = {1, 0, -1, 0, 1};\n int n, m;\n int cutOffTree(vector<vector<int>>& f) {\n n = f.size(), m = f[0].size();\n int cur = 0, result = 0;\n for(int i = 0; i < n; i++)\n for(int j = 0; j < m; j++)\n if(f[i][j] > 1)\n hash[f[i][j]] = i * m + j;\n \n for(auto& a: hash){\n int steps = helper(f, cur, a.second);\n if(steps == -1e9) return -1;\n result += steps;\n cur = a.second;\n }\n return result;\n }\n \n int helper(vector<vector<int>>& f, int cur, int target){\n queue<int> q;\n int steps = 0;\n q.push({cur});\n vector<vector<bool>> vis(n, vector<bool>(m));\n while(!q.empty()){\n int sz = q.size();\n while(sz--){\n int pos = q.front(), r = pos / m, c = pos % m;\n q.pop();\n if(pos == target)\n return steps;\n for(int k = 0; k < 4; k++){\n int nr = r + DIR[k], nc = c + DIR[k + 1];\n if(nr < 0 || nr == n || nc < 0 || nc == m || vis[nr][nc] || !f[nr][nc])\n continue;\n q.push({nr * m + nc});\n vis[nr][nc] = true;\n }\n }\n steps++;\n }\n return -1e9;\n }\n};\n```
1
0
['Breadth-First Search', 'C', 'C++']
0
cut-off-trees-for-golf-event
JAVA simple and fast with explanation and comments
java-simple-and-fast-with-explanation-an-2uli
Overview\n\nMy solution uses a BFS algorithm to find the distance between 2 any trees and then creates a path from the origin to the final tree by going via all
craigforrest
NORMAL
2022-06-21T21:00:58.215893+00:00
2023-02-16T12:39:09.791422+00:00
499
false
# Overview\n\nMy solution uses a BFS algorithm to find the distance between 2 any trees and then creates a path from the origin to the final tree by going via all the trees in the correct order.\n\n---\n\n# Step by Step\n1. Find all trees (all heights > 1 in the forest) and store in a list for sorting (with the height cached in the int[])\n2. Starting from (0, 0) get the distance between our current postion and the next tree (T1)\n3. Set current position to be the tree T1, and then repeat\n4. If any distance is -1, that means we can\'t find a valid path so we should return -1;\n5. Sum all paths together and return the result\n\n---\n# The Code\n\n```\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n List<int[]> trees = new ArrayList();\n \n\t\t// Find all trees\n for(int i = 0; i < forest.size(); i++)\n for(int j = 0; j < forest.get(0).size(); j++)\n if (forest.get(i).get(j) > 1)\n trees.add(new int[]{i, j, forest.get(i).get(j)});\n \n\t\t// Sort trees based on height\n trees.sort((a, b) -> Integer.compare(a[2], b[2]));\n \n int dist = 0;\n \n\t\t// Set current postion to be the origin\n int[] currPos = new int[]{0, 0};\n \n for(int[] tree : trees) {\n int d = getDist(forest, currPos, tree);\n\t\t\t// If we cannot find a path, return -1\n if (d == -1) return -1;\n dist+= d;\n\t\t\t// Set current position to be this tree\n currPos= tree;\n }\n \n return dist;\n }\n \n\t// Standard Breadth First Search algorithm\n private int getDist(List<List<Integer>> forest, int[] aPos, int[] bPos) {\n int aR = aPos[0];\n int aC = aPos[1];\n int bR = bPos[0];\n int bC = bPos[1];\n \n boolean[][] seen = new boolean[forest.size()][forest.get(0).size()];\n \n Queue<int[]> q = new LinkedList();\n q.offer(new int[]{aR, aC});\n \n int steps = 0;\n while(!q.isEmpty()) {\n int size = q.size();\n \n\t\t\t// Search through all positions in queue in 1 step\n for(int i = 0; i < size; i++) {\n int[] pos = q.poll();\n int r = pos[0];\n int c = pos[1];\n\t\t\t\t\n\t\t\t\t// If we have found target, return steps\n if (r == bR && c == bC) return steps;\n \n\t\t\t\t// validate position\n if (r < 0 || r >= forest.size() || c < 0 || c >= forest.get(0).size()) continue;\n if (seen[r][c]) continue;\n if (forest.get(r).get(c) == 0) continue;\n \n seen[r][c] = true;\n \n\t\t\t\t// Expand into 4 directions\n q.offer(new int[]{r+1, c});\n q.offer(new int[]{r-1, c});\n q.offer(new int[]{r, c+1});\n q.offer(new int[]{r, c-1});\n }\n \n steps++;\n }\n \n\t\t// If we haven\'t found target and no more positions to check, return -1\n return -1;\n }\n}\n```
1
0
['Breadth-First Search', 'Java']
1
cut-off-trees-for-golf-event
BFS C++
bfs-c-by-motorbreathing-kb0x
\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& f) {\n vector<int> trees;\n for (auto& v : f) {\n for (int x : v)
motorbreathing
NORMAL
2022-06-11T06:38:04.056428+00:00
2022-06-11T06:38:04.056466+00:00
111
false
```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& f) {\n vector<int> trees;\n for (auto& v : f) {\n for (int x : v) {\n if (x > 1)\n trees.push_back(x);\n }\n }\n sort(trees.begin(), trees.end());\n int treecounter = 0;\n int visited[51][51] = { 0 };\n queue<tuple<int, int, int>> q;\n q.push({0, 0, trees[0]});\n vector<vector<int>> dirs = {{-1 , 0}, {0, -1}, {1, 0}, {0, 1}};\n int steps = 0;\n while (q.size()) {\n int size = q.size();\n while (size--) {\n auto[x, y, t] = q.front();\n q.pop();\n // Discontinue this search as the corresponding\n // tree is no more\n if (trees[treecounter] != t)\n continue;\n // Found tree; cut tree\n if (f[x][y] == t) {\n f[x][y] = 1;\n treecounter++;\n if (treecounter == trees.size())\n return steps;\n // Next tree to target\n t = trees[treecounter];\n }\n for (auto& d : dirs) {\n int nx = x + d[0];\n int ny = y + d[1];\n if (nx < 0 || ny < 0 || nx == f.size() || ny == f[0].size())\n continue;\n if (f[nx][ny] == 0)\n continue;\n // If we\'ve been here before looking for the same tree\n if (visited[nx][ny] == t)\n continue;\n visited[nx][ny] = t;\n q.push({nx, ny, t});\n }\n }\n steps++;\n }\n return -1;\n }\n};\n```
1
0
[]
0
cut-off-trees-for-golf-event
Java - Priority Queue + BFS
java-priority-queue-bfs-by-adityasharma1-5xim
\npublic int shortestPathBfs(int[] start, int[] end, List<List<Integer>> forest) {\n int n = forest.size();\n int m = forest.get(0).size();\n
adityasharma15
NORMAL
2022-05-29T12:03:01.053119+00:00
2022-05-29T12:03:01.053163+00:00
272
false
```\npublic int shortestPathBfs(int[] start, int[] end, List<List<Integer>> forest) {\n int n = forest.size();\n int m = forest.get(0).size();\n boolean[][] visited = new boolean[n][m];\n for(int i = 0; i<n; i++) {\n for(int j = 0; j<m; j++) {\n visited[i][j] = false;\n }\n }\n\n int[][] matrixTraversal = {{0,-1}, {-1, 0}, {0, 1}, {1, 0}};\n Queue<int[]> bfs = new LinkedList<>();\n bfs.add(new int[]{start[0], start[1], 0});\n visited[start[0]][start[1]] = true;\n\n while(!bfs.isEmpty()) {\n int[] tree = bfs.poll();\n if(tree[0] == end[0] && tree[1] == end[1]) {\n return tree[2];\n }\n\n /*\n marking visited as true in loop only as we will be reaching the node in the shortest distance in first visit itself.\n */\n for(int i = 0; i<4; i++) {\n int x = tree[0] + matrixTraversal[i][0];\n int y = tree[1] + matrixTraversal[i][1];\n if(x >=0 && y >=0 && x<n && y<m && forest.get(x).get(y)!=0 && !visited[x][y]) {\n bfs.add(new int[]{x, y, tree[2] + 1});\n visited[x][y] = true;\n }\n }\n }\n\n return -1;\n }\n\n\n\n public int cutOffTree(List<List<Integer>> forest) {\n int n = forest.size();\n int m = forest.get(0).size();\n PriorityQueue<int[]> trees = new PriorityQueue<>((a,b) -> {\n if(a[2] > b[2]) {\n return 1;\n }\n return -1;\n });\n\n for(int i = 0; i<n; i++) {\n for(int j = 0; j<m; j++) {\n if(forest.get(i).get(j) > 1) {\n trees.add(new int[]{i, j, forest.get(i).get(j)});\n }\n }\n }\n\n int[] start = new int[]{0, 0, forest.get(0).get(0)};\n int totalSteps = 0;\n while(!trees.isEmpty()) {\n int[] end = trees.poll();\n int steps = shortestPathBfs(start, end, forest);\n if(steps == -1) {\n return -1;\n }\n totalSteps += steps;\n\n start[0] = end[0];\n start[1] = end[1];\n }\n\n return totalSteps;\n }\n```
1
0
['Breadth-First Search', 'Heap (Priority Queue)', 'Java']
0
cut-off-trees-for-golf-event
Confuse about the this test case, can anyone help me?
confuse-about-the-this-test-case-can-any-eswq
let\'s see this test case\n\n[\n[10,2,3],\n[0,0,4],\n[7,6,5]]\n\n\nI run the code and the expected output would be 12 from Leetcode, I thought it would be -1 si
ganjarpranowo222
NORMAL
2022-05-28T06:56:33.966845+00:00
2022-05-28T06:56:33.966882+00:00
112
false
let\'s see this test case\n```\n[\n[10,2,3],\n[0,0,4],\n[7,6,5]]\n```\n\nI run the code and the expected output would be 12 from Leetcode, I thought it would be -1 since from 0,0 it cannot go to anywhere.\n\nHow do we explain this test case?
1
0
[]
1
cut-off-trees-for-golf-event
Python BFS + MinHeap
python-bfs-minheap-by-liufangy-0to4
\nclass Solution(object):\n def cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: int\n """\n def
liufangy
NORMAL
2022-03-18T16:09:39.853697+00:00
2022-03-18T16:09:39.853728+00:00
329
false
```\nclass Solution(object):\n def cutOffTree(self, forest):\n """\n :type forest: List[List[int]]\n :rtype: int\n """\n def bfs(i, j, destx, desty):\n q = deque()\n visited = set()\n q.append((i, j, 0))\n while q:\n x, y, step = q.popleft()\n if x == destx and y == desty:\n return step\n for dirx, diry in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n curx, cury = dirx + x, diry + y\n \n if 0 <= curx < m and 0 <= cury < n and forest[curx][cury] != 0 and (curx, cury) not in visited:\n q.append((curx, cury, step + 1))\n visited.add((curx, cury))\n return -1\n \n \n m, n = len(forest), len(forest[0])\n \n heap = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n heapq.heappush(heap, (forest[i][j], i, j))\n \n res = 0\n i, j = 0, 0\n while heap:\n _, destx, desty = heapq.heappop(heap)\n step = bfs(i, j, destx, desty)\n # print i, j, destx, desty, step\n if step < 0:\n return -1\n res += step\n i, j = destx, desty\n return res\n```
1
0
['Breadth-First Search', 'Heap (Priority Queue)', 'Python']
0
cut-off-trees-for-golf-event
Python (Use collections.deque instead of queue.Queue) NO TLE( BFS/PriorityQueue)
python-use-collectionsdeque-instead-of-q-58f0
Runtime: 5734 ms, faster than 79.53% of Python3 online submissions for Cut Off Trees for Golf Event.\nMemory Usage: 14.4 MB, less than 96.34% of Python3 online
0merjavaid
NORMAL
2022-02-06T14:44:04.733991+00:00
2022-02-06T14:46:19.166704+00:00
139
false
Runtime: 5734 ms, faster than 79.53% of Python3 online submissions for Cut Off Trees for Golf Event.\nMemory Usage: 14.4 MB, less than 96.34% of Python3 online submissions for Cut Off Trees for Golf Event.\n\nI was using queue.Queue() and got TLE, replaced that with collections.deque and reduced time from TLE to 2000 ms\n```\nfrom queue import Queue\nclass Solution:\n # returns sorted trees by height\n def get_priority(self, forest):\n m, n = len(forest), len(forest[0])\n priority = []\n for r in range(m):\n for c in range(n):\n v = forest[r][c]\n if v > 1:\n priority.append((v)) \n priority.sort()\n return priority\n \n def cutOffTree(self, forest: List[List[int]]) -> int:\n n = len(forest)\n m = len(forest[0])\n priority = self.get_priority(forest)\n steps = 0\n \n i,j = 0, 0\n\t\t# next tree in line\n for node in priority:\n to_find =node \n visited = [[0]*m for _ in range(n)]\n q = collections.deque([(i, j, steps)])\n q.append((i,j, steps))\n found = False # if found is False that means blocked by 0s\n while q:\n i, j, steps = q.popleft()\n if forest[i][j] == to_find: # Tree found so move to next tree\n found = True\n break\n \n if forest[i][j] == 0: # Skip 0s\n continue\n if i + 1 < n and forest[i+1][j] !=0 and not visited[i+1][j]:\n q.append((i+1, j, steps+1))\n visited[i+1][j]= 1\n if i - 1 >= 0 and forest[i-1][j] !=0 and not visited[i-1][j]:\n q.append((i-1, j, steps+1))\n visited[i-1][j]= 1\n if j + 1 < m and forest[i][j+1] !=0 and not visited[i][j+1]:\n q.append((i, j + 1, steps+1))\n visited[i][j+1]= 1\n if j - 1 >= 0 and forest[i][j-1] !=0 and not visited[i][j-1]:\n q.append((i, j-1, steps+1))\n visited[i][j-1]= 1\n \n if not found: return -1\n return steps \n \n```
1
0
[]
0
cut-off-trees-for-golf-event
c++ solution using bfs
c-solution-using-bfs-by-dilipsuthar60-487e
\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>&mat)\n {\n vector<pair<int,int>>d={{-1,0},{1,0},{0,-1},{0,1}};\n int n=mat.
dilipsuthar17
NORMAL
2022-01-07T13:40:51.154523+00:00
2022-01-07T13:40:51.154551+00:00
619
false
```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>&mat)\n {\n vector<pair<int,int>>d={{-1,0},{1,0},{0,-1},{0,1}};\n int n=mat.size();\n int m=mat[0].size();\n vector<vector<long long>>v;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(mat[i][j]>1)\n {\n v.push_back({i,j,mat[i][j]});\n }\n }\n }\n auto bfs=[&](int st1,int st2,int ds1,int ds2)\n {\n queue<pair<int,int>>q;\n q.push({st1,st2});\n int level=0;\n vector<vector<bool>>vis(n+2,vector<bool>(m+2,false));\n vis[st1][st2]=true;\n while(q.size())\n {\n int size=q.size();\n for(int i=0;i<size;i++)\n {\n auto temp=q.front();\n q.pop();\n long long x=temp.first;\n long long y=temp.second;\n if(x==ds1&&y==ds2)\n {\n return level;\n }\n for(auto &it:d)\n {\n long long nx=x+it.first;\n long long ny=y+it.second;\n if(nx>=0&&ny>=0&&nx<n&&ny<m&&mat[nx][ny]>=1&&vis[nx][ny]==false)\n {\n q.push({nx,ny});\n vis[nx][ny]=true;\n }\n }\n }\n level++;\n }\n return -1;\n };\n sort(v.begin(),v.end(),[&](auto &v1,auto &v2){return v1[2]<v2[2];});\n long long st1=0;\n long long st2=0;\n long long count=0;\n for(int i=0;i<v.size();i++)\n {\n long long ds1=v[i][0];\n long long ds2=v[i][1];\n long long step=bfs(st1,st2,ds1,ds2);\n if(step<0)\n {\n return -1;\n }\n count+=step;\n st1=ds1;\n st2=ds2;\n }\n return count;\n }\n};\n```
1
0
['Breadth-First Search', 'C', 'Sorting', 'C++']
0
cut-off-trees-for-golf-event
C# solution
c-solution-by-ema123-98dk
\npublic class Solution {\n \n private readonly IList<int[]> _directions = new List<int[]>()\n {\n new int[] { 1, 0 },\n new int[] { -1,
ema123
NORMAL
2021-12-11T20:42:45.665076+00:00
2021-12-11T20:42:45.665120+00:00
92
false
```\npublic class Solution {\n \n private readonly IList<int[]> _directions = new List<int[]>()\n {\n new int[] { 1, 0 },\n new int[] { -1, 0 },\n new int[] { 0, 1 }, \n new int[] { 0, -1 }\n };\n \n public int CutOffTree(IList<IList<int>> forest) {\n \n if (forest == null)\n {\n throw new ArgumentNullException("Parameter cannot be null", nameof(forest));\n }\n \n return CutOffTreeBfs(forest);\n }\n \n private int CutOffTreeBfs(IList<IList<int>> forest)\n {\n // Note that here we will store <height:coordinates>\n var treeMap = new Dictionary<int, int[]>();\n for (var row = 0; row < forest.Count; row++)\n {\n for (var col = 0; col < forest[0].Count; col++)\n {\n // Note that we need to store only trees of height greater than one, since anything else is not a tree and either just grass or a barrier\n if (forest[row][col] > 1)\n {\n // Note that we are guaranteed unique heights\n treeMap.Add(forest[row][col], new int[] { row, col });\n }\n }\n }\n \n var result = 0;\n var startRow = 0;\n var startCol = 0;\n var sortedTreeMap = treeMap.OrderBy(kvp => kvp.Key);\n \n foreach (var kvp in sortedTreeMap)\n {\n var endRow = kvp.Value[0];\n var endCol = kvp.Value[1];\n \n var steps = GetShortestPathBfs(forest, startRow, startCol, endRow, endCol);\n if (steps == -1)\n {\n return -1;\n }\n \n result += steps;\n startRow = endRow;\n startCol = endCol;\n }\n \n return result;\n }\n \n private int GetShortestPathBfs(IList<IList<int>> forest, int startRow, int startCol, int endRow, int endCol)\n {\n if (startRow == endRow && startCol == endCol)\n {\n return 0;\n }\n \n var queue = new Queue<int[]>();\n queue.Enqueue(new int[] { startRow, startCol });\n \n var visited = new int[forest.Count, forest[0].Count];\n visited[startRow, startCol] = 1;\n \n var level = 0;\n \n while (queue.Count > 0)\n {\n level++;\n var size = queue.Count;\n while (size > 0)\n {\n var oldNode = queue.Dequeue();\n var oldRow = oldNode[0];\n var oldCol = oldNode[1];\n \n foreach (var d in _directions)\n {\n var newRow = oldRow + d[0];\n var newCol = oldCol + d[1];\n \n if (newRow >= 0 && newRow < forest.Count && newCol >= 0 && newCol < forest[0].Count && forest[newRow][newCol] != 0 && visited[newRow, newCol] == 0)\n { \n if (newRow == endRow && newCol == endCol)\n {\n return level;\n } \n \n visited[newRow, newCol] = 1; \n queue.Enqueue(new int[] { newRow, newCol });\n }\n }\n \n size--;\n }\n }\n \n return -1;\n }\n \n}\n```
1
0
[]
0
cut-off-trees-for-golf-event
(C++) 675. Cut Off Trees for Golf Event
c-675-cut-off-trees-for-golf-event-by-qe-rr3u
\n\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int m = forest.size(), n = forest[0].size(), dir[5] = {-1, 0, 1, 0, -1
qeetcode
NORMAL
2021-11-17T03:21:17.677640+00:00
2021-11-17T03:21:17.677678+00:00
364
false
\n```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n int m = forest.size(), n = forest[0].size(), dir[5] = {-1, 0, 1, 0, -1}; \n bool seen[m][n]; \n \n auto fn = [&](pair<int, int>& start, pair<int, int>& end) {\n int ans = 0; \n memset(seen, false, sizeof(seen)); \n seen[start.first][start.second] = true; \n queue<pair<int, int>> q; q.push(start); \n for (; q.size(); ++ans) \n for (int sz = q.size(); sz; --sz) {\n auto [i, j] = q.front(); q.pop(); \n if (i == end.first && j == end.second) return ans; \n for (int k = 0; k < 4; ++k) {\n int ii = i + dir[k], jj = j + dir[k+1]; \n if (0 <= ii && ii < m && 0 <= jj && jj < n && forest[ii][jj] != 0 && !seen[ii][jj]) {\n seen[ii][jj] = true; \n q.emplace(ii, jj); \n }\n }\n }\n return -1; \n }; \n \n vector<tuple<int, int, int>> vals; \n for (int i = 0; i < m; ++i) \n for (int j = 0; j < n; ++j) \n if (forest[i][j] > 1) vals.emplace_back(forest[i][j], i, j); \n sort(vals.begin(), vals.end()); \n \n int ans = 0; \n pair<int, int> start = {0, 0}; \n for (auto& [v, i, j] : vals) {\n pair<int, int> end = {i, j}; \n int val = fn(start, end); \n if (val == -1) return -1; \n ans += val; \n start = end; \n }\n return ans; \n }\n};\n```
1
0
['C']
0
cut-off-trees-for-golf-event
C++ || Using BFS & Priority Queue
c-using-bfs-priority-queue-by-shinigami_-26xb
\n### Do Upvote if Helpful :-)\nclass Solution {\n int n,m;\n int d[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};\npublic:\n \n bool valid(int a,int b,int n,
Shinigami_11
NORMAL
2021-10-31T03:53:43.298249+00:00
2021-10-31T03:53:43.298320+00:00
193
false
\n### Do Upvote if Helpful :-)\nclass Solution {\n int n,m;\n int d[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};\npublic:\n \n bool valid(int a,int b,int n,int m){\n \n return (a>=0&&a<n&&b>=0&&b<m);\n }\n \n int bfs(vector<vector<int>> &fo,pair<int,int> start,pair<int,int> target){\n \n if(start.first==target.first && start.second==target.second)\n return 0;\n \n vector<vector<bool>> used(n,vector<bool>(m,false));\n used[start.first][start.second] = true;\n \n int steps = 0;\n queue<pair<int,int>> q;\n \n q.push(start);\n while(!q.empty()){\n \n steps++;\n int size = q.size();\n \n while(size--){\n auto curr = q.front();\n q.pop();\n \n for(int i=0;i<4;i++){\n int x = curr.first+d[i][0];\n int y = curr.second+d[i][1];\n \n if(valid(x,y,n,m) && !used[x][y] && fo[x][y]>0){\n \n if(x==target.first && y==target.second)\n return steps;\n \n used[x][y] = true;\n q.push({x,y}); \n }\n }\n }\n }\n return -1;\n }\n \n int cutOffTree(vector<vector<int>>& forest) {\n \n n = forest.size();\n m = forest[0].size();\n \n if(n==0)\n return -1;\n \n typedef tuple<int,int,int> hxy;\n priority_queue<hxy,vector<hxy>,greater<hxy>> pq;\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(forest[i][j]>1) \n pq.push({forest[i][j],i,j});\n }\n }\n \n int ans = 0;\n pair<int,int> start{0,0};\n pair<int,int> target;\n \n while(!pq.empty()){\n auto curr = pq.top();\n pq.pop();\n \n target = {get<1>(curr),get<2>(curr)};\n int steps = bfs(forest,start,target);\n \n if(steps==-1)\n return -1;\n \n ans+=steps;\n start = target;\n }\n \n \n return ans;\n }\n};
1
0
['Queue', 'Heap (Priority Queue)']
0
cut-off-trees-for-golf-event
C++ Solution, Priority Queue + BFS
c-solution-priority-queue-bfs-by-jahed32-7yw9
My C++ solution using priority queue and bfs.\n\n\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) \n {\n m = forest.size()
jahed321
NORMAL
2021-10-30T18:36:12.481012+00:00
2021-10-30T18:36:12.481050+00:00
254
false
My C++ solution using priority queue and bfs.\n\n```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) \n {\n m = forest.size();\n if (m == 0) return -1;\n n = forest[0].size();\n \n typedef tuple<int, int, int> HeightXY;\n priority_queue<HeightXY, vector<HeightXY>, greater<HeightXY>> minHeap;\n \n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++)\n {\n if (forest[i][j] > 1) // contains tree\n {\n minHeap.push({forest[i][j], i, j});\n }\n }\n }\n \n int res = 0;\n \n // Starting from [0,0] find the min steps to reach 1st target from min heap top.\n // Next start from this 1st target which becomes starting point for next iteration\n // and find min steps to reach 2nd target from min heap (which is current top now).\n // Continue until min heap is empty and accumulate these steps.\n pair<int, int> start{0, 0};\n pair<int, int> target;\n int steps = 0;\n while(!minHeap.empty())\n {\n auto cur = minHeap.top();\n minHeap.pop();\n \n target = {get<1>(cur), get<2>(cur)}; // row, col\n steps = bfs(forest, start, target);\n \n if (steps == -1) return -1;\n \n res += steps;\n start = target;\n }\n \n return res;\n }\n \n int bfs(vector<vector<int>>& forest, pair<int, int>& start, pair<int, int>& target)\n {\n if (start.first == target.first && start.second == target.second)\n return 0;\n \n vector<vector<bool>> visited(m, vector<bool>(n, false));\n \n queue<pair<int, int>> q;\n q.push(start);\n visited[start.first][start.second] = true;\n \n int steps = 0;\n while (!q.empty())\n {\n steps++;\n int size = q.size();\n while (size--)\n {\n auto cur = q.front();\n q.pop();\n \n for (auto dir : dirs)\n {\n int x = cur.first + dir.first;\n int y = cur.second + dir.second;\n \n // forest[x][y] = 0 cannot be walked through\n if (x >= 0 && x < m && y >= 0 && y < n && forest[x][y] > 0 && !visited[x][y])\n {\n if (x == target.first && y == target.second)\n return steps;\n \n visited[x][y] = true;\n q.push({x, y});\n }\n }\n }\n }\n \n return -1;\n }\n \nprivate:\n int m;\n int n;\n vector<pair<int, int>> dirs = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };\n};\n```
1
1
['Breadth-First Search', 'C', 'Heap (Priority Queue)']
0
cut-off-trees-for-golf-event
C# Solution using BFS
c-solution-using-bfs-by-koliter-tonu
Not quite sure of the complexity though it might be T: O(nmlogn).\n\nInterestingly, I had a timeout error because I was using a List as Visited. That taught me
Koliter
NORMAL
2021-09-16T11:56:46.018511+00:00
2021-09-16T11:56:46.018547+00:00
124
false
Not quite sure of the complexity though it might be T: O(n*m*logn).\n\nInterestingly, I had a timeout error because I was using a List as Visited. That taught me to use a bool[] in order to keep the values instead of a list as when searching, it\'s much faster.\n\n```\npublic class Solution {\n \n private List<(int r, int c)> Directions = new List<(int r, int c)>{\n (0, 1),\n (0, -1),\n (1, 0),\n (-1, 0)\n };\n \n public int CutOffTree(IList<IList<int>> forest) {\n \n var treesToCut = new List<int>();\n for(int i = 0; i < forest.Count; i++)\n for(int j = 0; j < forest[0].Count; j++)\n if(forest[i][j] > 1)\n treesToCut.Add(forest[i][j]);\n \n treesToCut = treesToCut.OrderBy(x => x).ToList();\n \n // BFS\n var totalSteps = 0;\n (int r, int c) location = (0, 0);\n foreach(var tree in treesToCut)\n {\n var queue = new Queue<(int r, int c)>();\n var visited = new bool[forest.Count, forest[0].Count];\n queue.Enqueue(location);\n visited[location.r, location.c] = true;;\n \n var currentSteps = 0;\n var found = false;\n \n if(forest[location.r][location.c] == tree)\n found = true;\n \n while(queue.Count != 0 && !found)\n {\n currentSteps++;\n \n var currentLevelNodes = queue.Count();\n while(currentLevelNodes > 0 && !found)\n {\n var curr = queue.Dequeue();\n \n foreach(var dir in Directions)\n {\n var r = curr.r + dir.r;\n var c = curr.c + dir.c;\n \n if(0 <= r && r < forest.Count \n && 0 <= c && c < forest[0].Count \n && !visited[r, c] && forest[r][c] > 0){\n queue.Enqueue((r, c));\n visited[r, c] = true;;\n if(forest[r][c] == tree){\n location = (r, c);\n found = true;\n }\n }\n }\n currentLevelNodes--;\n }\n }\n \n if(!found)\n return -1;\n \n totalSteps += currentSteps;\n }\n return totalSteps;\n }\n}\n```
1
0
[]
0
cut-off-trees-for-golf-event
Python 3: BFS timeout issue, need help
python-3-bfs-timeout-issue-need-help-by-xasij
Can any one tell why this code is timing out. It works fine for smaller input however it seems to be taking lot of time for a bigger input. What am I missing he
arjunankathatti
NORMAL
2021-08-28T00:51:36.481355+00:00
2021-08-28T00:51:36.481385+00:00
181
false
Can any one tell why this code is timing out. It works fine for smaller input however it seems to be taking lot of time for a bigger input. What am I missing here?\nYour input is highly appreciated.\n```\nclass Solution:\n def __init__(self):\n self.offsets = [(1,0),(-1,0),(0,1),(0,-1)]\n def cutOffTree(self, forest: List[List[int]]) -> int:\n # traverse the forest \n # get all trees to be cut\n n = len(forest)\n m = len(forest[0])\n treesToBeCut = []\n for i in range(n):\n for j in range(m):\n if forest[i][j] > 1:\n treesToBeCut.append((i, j, forest[i][j]))\n \n # sort these trees to be cut in ascending order \n # shortest first and the longest one last \n treesToBeCut.sort(key=lambda x: x[2])\n #print(treesToBeCut)\n \n # use this BFS to find the shortest path to all the \n # trees, two at a time starting from 0, 0\n \n # start from the begining and go through\n # all the trees that needs to be cut in the ascending order\n src_x = src_y = totalDist = 0\n for cur_x, cur_y, h in treesToBeCut:\n d = self.bfs(forest, src_x, src_y, cur_x, cur_y, n, m)\n if d < 0:\n # if there is no path between source cell to target cell\n return -1\n \n # add the distance to total distance\n totalDist += d\n \n # change the source cell to to be current cell\n src_x = cur_x\n src_y = cur_y\n \n return totalDist\n \n # to find the shortest distance between any two nodes\n # we will use BFS\n def bfs(self, forest, src_x, src_y, target_x, target_y, n, m):\n print((src_x, src_y), (target_x, target_y))\n q = collections.deque([(src_x, src_y)])\n seen = set()\n level = 0\n while q:\n s = len(q)\n for i in range(s):\n cur_x, cur_y = q.popleft()\n # if current cell is the target cell\n if cur_x == target_x and cur_y == target_y:\n return level\n\n # mark current node as visited\n seen.add((cur_x, cur_y))\n\n # find all the neighbours\n for rowOffSet, colOffSet in self.offsets:\n nx = cur_x + rowOffSet\n ny = cur_y + colOffSet\n\n # if not valid do nothing \n if nx < 0 or nx >= n or ny < 0 or ny >= m or forest[nx][ny] == 0 or (nx, ny) in seen:\n continue\n\n # add the valid unseen node to the queue and increase the level\n q.append((nx, ny))\n \n # increment level\n level += 1\n \n # when there is no path between source and target cells\n return -1\n \n```
1
0
[]
0
cut-off-trees-for-golf-event
Python Sorted Trees + BFS
python-sorted-trees-bfs-by-ingared-qoxe
The problem dictates the path of ascending tree path (unique heights of tree). Hence we just need to find steps between current_tree and next_tree in the sorted
ingared
NORMAL
2021-08-16T20:35:20.371285+00:00
2021-08-16T20:35:20.371316+00:00
297
false
The problem dictates the path of ascending tree path (unique heights of tree). Hence we just need to find steps between current_tree and next_tree in the sorted trees. Summing up all should give us the total steps. To find path between tree and next_tree we could use any search(dfs/bfs) but bfs would be optimal. If no path exists between any two consequitve nodes in the sorted trees, it implies no solution exist. \n\n```\nclass Solution:\n \n def pathExists(self, src, dst, forest):\n \n rows = len(forest)\n cols = len(forest[0])\n \n dst_x = dst[1]\n dst_y = dst[2]\n \n def bfs(q, visited):\n while (q):\n (x,y, count) = q.popleft()\n \n if (x,y) == (dst_x, dst_y):\n return count\n\n dx, dy = 0, 1 \n for i in range(4):\n nx = x + dx\n ny = y + dy\n if (0 <= nx < rows) and (0 <= ny < cols) and (forest[nx][ny] >= 1) and (nx, ny) not in visited:\n visited.add((nx, ny))\n q.append((nx, ny, count + 1))\n dx, dy = -dy, dx\n \n return -1\n \n v, x, y = src\n visited = {(x,y)}\n q = collections.deque()\n q.append((x,y,0))\n return bfs(q, visited)\n \n def cutOffTree(self, forest: List[List[int]]) -> int:\n \n rows = len(forest)\n cols = len(forest[0])\n trees = sorted([(forest[i][j], i,j) for i in range(rows) for j in range(cols) if forest[i][j] > 1])\n \n start = (forest[0][0], 0 ,0)\n mn_steps = 0\n for next_tree in trees:\n steps = self.pathExists(start, next_tree, forest)\n start = next_tree\n forest[start[1]][start[2]] = 1\n if steps < 0:\n return -1\n else:\n mn_steps += steps\n \n return mn_steps\n```
1
0
[]
0
cut-off-trees-for-golf-event
Python BFS working solution
python-bfs-working-solution-by-gswe-i032
\n def cutOffTree(self, forest: List[List[int]]) -> int:\n rows = len(forest)\n cols = len(forest[0])\n def is_valid_move(row, col, matr
GSWE
NORMAL
2021-08-05T18:25:26.677213+00:00
2021-08-05T20:00:06.242104+00:00
281
false
```\n def cutOffTree(self, forest: List[List[int]]) -> int:\n rows = len(forest)\n cols = len(forest[0])\n def is_valid_move(row, col, matrix, visited):\n nonlocal rows, cols\n if new_row >= rows or new_row < 0 or new_col >= cols or new_col < 0: return False\n if (new_row, new_col) in visited: return False\n if matrix[row][col] == 0: return False\n return True\n trees = []\n for r in range(rows):\n for c in range(cols):\n if forest[r][c] > 1: trees.append(forest[r][c])\n trees.sort()\n index = 0\n steps = 0\n start_node = (0,0)\n found_flag = True\n while index < len(trees):\n start_row, start_col = start_node\n if not found_flag: break\n found_flag = False\n queue = deque([(start_row, start_col, 0)])\n visited = set([(start_row, start_col)])\n while queue:\n # look for current_tree\n r,c,s = queue.popleft()\n if forest[r][c] == trees[index]:\n forest[r][c] = 1\n index += 1\n steps += s\n found_flag = True\n start_node = (r,c)\n break\n for direction_row, direction_col in [(-1,0), (1,0), (0,1), (0,-1)]:\n new_row, new_col = direction_row + r, direction_col + c\n if is_valid_move(new_row, new_col, forest, visited):\n queue.append((new_row, new_col, s+1))\n visited.add((new_row, new_col))\n return steps if index >= len(trees) else -1\n```
1
0
[]
0
cut-off-trees-for-golf-event
C++ || Simple Bfs based solution
c-simple-bfs-based-solution-by-sj4u-cefx
\nclass Solution {\npublic:\n \n \n int xp[4]={-1,1,0,0};\n int yp[4]={0,0,-1,1};\n \n int bfs(vector<vector<int>>& arr,int i,int j,int l,int m,
SJ4u
NORMAL
2021-07-30T12:14:37.768454+00:00
2021-07-30T12:14:37.768487+00:00
529
false
```\nclass Solution {\npublic:\n \n \n int xp[4]={-1,1,0,0};\n int yp[4]={0,0,-1,1};\n \n int bfs(vector<vector<int>>& arr,int i,int j,int l,int m,vector<vector<int>>&visited)\n {\n \n \n visited[i][j]=1;\n \n queue<pair<int,pair<int,int>>>q;\n q.push({0,{i,j}});\n \n int ans=-1;\n while(q.size())\n {\n int level=q.front().first;\n int x=q.front().second.first;\n int y=q.front().second.second;\n q.pop();\n \n \n \n visited[x][y]=1;\n \n if(x==l&&y==m)\n {\n ans=level;\n break;\n }\n \n for(int k=0;k<4;k++)\n {\n int u=x+xp[k],v=y+yp[k];\n \n if(u>=0&&v>=0&&u<arr.size()&&v<arr[0].size()&&!visited[u][v]&&arr[u][v])\n {\n \n visited[u][v]=1;\n q.push({level+1,{u,v}});\n }\n }\n\n }\n return ans; \n }\n \n \n \n \n int cutOffTree(vector<vector<int>>& arr) {\n int ans=0;\n \n vector<pair<int,pair<int,int>>>v;\n \n for(int i=0;i<arr.size();i++)\n for(int j=0;j<arr[i].size();j++)\n if(arr[i][j]>1)\n v.push_back({arr[i][j],{i,j}});\n \n \n v.push_back({0,{0,0}});\n sort(v.begin(),v.end());\n\n \n vector<vector<int>>visited;\n \n for(int i=0;i<v.size()-1;i++)\n {\n visited.clear();\n visited.resize(arr.size(),vector<int>(arr[0].size(),0));\n int k=bfs(arr,v[i].second.first,v[i].second.second,v[i+1].second.first,v[i+1].second.second,visited);\n if(k==-1)\n return -1;\n else\n ans+=k;\n }\n\n return ans;\n }\n};\n```
1
0
['Breadth-First Search', 'C']
0
cut-off-trees-for-golf-event
C++ | BFS+sort
c-bfssort-by-kena7-nkkm
\nclass Solution {\npublic:\n int dx[4]={1,0,0,-1};\n int dy[4]={0,1,-1,0};\n int m,n;\n bool isvalid(int i,int j)\n {\n if(i<0 || j<0 ||
kenA7
NORMAL
2021-07-30T11:28:04.409879+00:00
2021-07-30T11:28:04.409908+00:00
206
false
```\nclass Solution {\npublic:\n int dx[4]={1,0,0,-1};\n int dy[4]={0,1,-1,0};\n int m,n;\n bool isvalid(int i,int j)\n {\n if(i<0 || j<0 || i>=m || j>=n)\n return false;\n return true;\n }\n int BFS(int si,int sj,int di,int dj,vector<vector<int>>forest)\n {\n queue<pair<int,int>>q;\n q.push({si,sj});\n forest[si][sj]=0;\n int res=0;\n while(!q.empty())\n {\n int n=q.size();\n while(n--)\n {\n int i=q.front().first,j=q.front().second;\n q.pop();\n if(i==di && j==dj)\n return res;\n for(int k=0;k<4;k++)\n {\n int x=i+dx[k],y=j+dy[k];\n if(isvalid(x,y) && forest[x][y]!=0)\n {\n forest[x][y]=0;\n q.push({x,y});\n }\n }\n }\n res++;\n }\n return -1;\n }\n int cutOffTree(vector<vector<int>>& forest) \n {\n vector<vector<int>>v;\n m=forest.size(),n=forest[0].size();\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(forest[i][j]>1)\n v.push_back({forest[i][j],i,j});\n }\n }\n sort(v.begin(),v.end());\n int i=0,j=0,res=0;\n for(auto p:v)\n {\n int dist=BFS(i,j,p[1],p[2],forest);\n if(dist==-1)\n return -1;\n res+=dist;\n i=p[1],j=p[2];\n }\n return res;\n }\n};\n```
1
0
[]
0
cut-off-trees-for-golf-event
Java BFS + PriorityQueue + clean code
java-bfs-priorityqueue-clean-code-by-tan-3djv
\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n // if(forest.get(0).get(0) == 0)\n // return -1;\n \n
tanmaythaakur
NORMAL
2021-06-25T16:35:31.275113+00:00
2021-06-25T16:35:31.275145+00:00
393
false
```\nclass Solution {\n public int cutOffTree(List<List<Integer>> forest) {\n // if(forest.get(0).get(0) == 0)\n // return -1;\n \n int m = forest.size(), n = forest.get(0).size();\n int ans = 0, steps = 0;\n \n PriorityQueue<Integer> pq = new PriorityQueue<>();\n Queue<int[]> q = new LinkedList<>();\n boolean vis[][] = new boolean[m][n];\n \n int []dx = {0, 0, -1, 1};\n int []dy = {1, -1, 0, 0};\n \n for(int i=0; i<m; i++)\n for(int j=0; j<n; j++)\n if(forest.get(i).get(j) > 1)\n pq.offer(forest.get(i).get(j));\n \n q.add(new int[]{0, 0});\n vis[0][0] = true;\n \n \n while(!q.isEmpty()) {\n int sz = q.size();\n \n for(int c=0; c<sz; c++) {\n int x = q.peek()[0], y = q.peek()[1];\n q.remove();\n \n // System.out.println(x + " " + y);\n if(forest.get(x).get(y) == pq.peek()) {\n pq.poll();\n forest.get(x).set(y, 1);\n ans += steps;\n if(pq.size() == 0)\n return ans;\n vis = new boolean[m][n];\n vis[x][y] = true;\n q.clear();\n steps = -1;\n q.add(new int[]{x, y});\n break;\n }\n \n for(int i=0; i<4; i++) {\n int nx = x + dx[i], ny = y + dy[i];\n \n if(nx < 0 || ny < 0 || nx >= m || ny >= n || forest.get(nx).get(ny) == 0 || vis[nx][ny]) {\n continue;\n }\n q.add(new int[]{nx, ny});\n vis[nx][ny] = true;\n }\n }\n \n steps++;\n }\n \n return -1;\n }\n}\n```
1
1
[]
0
cut-off-trees-for-golf-event
[Python3] Priority queue + Bidirectional BFS
python3-priority-queue-bidirectional-bfs-2onb
The problem is actually easy with this one intuition. Since, the trees have to be cut in increasing order of height and the heights are distinct, there is alway
redsand
NORMAL
2021-06-04T17:56:58.793844+00:00
2021-06-04T17:58:19.607602+00:00
204
false
The problem is actually easy with this one intuition. Since, the trees have to be cut in increasing order of height and the heights are distinct, there is always only one cell we need to visit next. The problem then becomes how fast can we get from the current cell to the next cell which is BFS! The problem reduces to performing X BFS calls where X is the number of trees.\n\nConsider the example\n```\n[5, 4, 6]\n[0, 0, 2]\n[10, 11, 12]\n```\n\nWe start at (0, 0) and the height is 5. But we cannot cut it yet as there is a tree with height 2 at (1, 2). So the first step is to get from (0, 0) to (1, 2). After getting to (1, 2) we cut the tree. The next shortest tree is at (0, 1) with a height of 4. So now we need to move from (1, 2) to (0, 1).\n\nThe order of the trees to cut can be maintained using a min heap. If at any point, we are not able to reach the next tree, just return -1. A bidirectional BFS helps speed up the search.\n\nTime Complexity: O((MN)^2 * lgMN)\nM is the number of rows and N is the number of columns\nAll the cells could be in the heap and processing all of them takes MN lgMN\nEach BFS search could take a maximum of MN time\n\nSpace complexity: O(MN)\nThe heap takes O(MN) space. One run of BFS takes O(MN) space and it is discarded once complete.\n\n```\nimport heapq\n\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n def bfs(start, end):\n if start == end:\n return 0\n \n fwd, rev = [start], [end]\n visited_fwd, visited_rev = set(fwd), set(rev)\n steps = 0\n while fwd:\n if len(fwd) > len(rev):\n fwd, rev = rev, fwd\n visited_fwd, visited_rev = visited_rev, visited_fwd\n \n nxt = []\n for i, k in fwd:\n for x, y in directions:\n nxt_i, nxt_k = i + x, k + y\n if 0 <= nxt_i < m and 0 <= nxt_k < n and forest[nxt_i][nxt_k] != 0 and (nxt_i, nxt_k) not in visited_fwd:\n if (nxt_i, nxt_k) in visited_rev:\n return steps + 1\n visited_fwd.add((nxt_i, nxt_k))\n nxt.append((nxt_i, nxt_k))\n \n steps += 1\n fwd = nxt\n \n return -1\n \n m, n = len(forest), len(forest[0])\n min_steps = 0\n directions = ((0, 1), (0, -1), (1, 0), (-1, 0))\n curr = (0, 0)\n \n heap = []\n for i, k in product(range(m), range(n)):\n if forest[i][k] > 1:\n heapq.heappush(heap, (forest[i][k], (i, k)))\n \n while heap:\n _, nxt = heapq.heappop(heap)\n min_steps_to_nxt = bfs(curr, nxt)\n if min_steps_to_nxt == -1:\n return -1\n \n min_steps += min_steps_to_nxt\n curr = nxt\n \n return min_steps\n```
1
0
[]
0
cut-off-trees-for-golf-event
Java solution, slow but clear. Coursera Princeton algorithms course
java-solution-slow-but-clear-coursera-pr-pco9
I am using Coursera algorithms (Princeton, Robert Sedgewick) course ideas so code should be easy to understand if you watched it.\nIdea is based on building a G
akumpan
NORMAL
2021-06-02T22:00:58.579598+00:00
2021-06-02T22:11:13.244539+00:00
283
false
I am using Coursera algorithms (Princeton, Robert Sedgewick) course ideas so code should be easy to understand if you watched it.\nIdea is based on building a Graph from the matrix using adjucencyMap representation and then use BFS to fins path from shortest tree to next shortest tree in this graph:\nStep 1a: build adjucency HashMap (graph) of cells we can visit\nStep 1b: build TreeMap (treeHeight, index) in order to know which trees to visit first \nStep 2: run BFS to find distance from start to shortestTree; start = shortestTreeIndex after\nStep 3: visit and cut trees in order from shortest one, if tree cannot be reached -> return -1\n\n**Note: this solution is extremely slow (bottom 5% on speed and memory by leetcode mertics)**\n\nIt supposed to be:\n```\nM == forest.length\nN == forest[i].length\nO(MN) -> building adjucency Map\nO(MN)*log(MN) -> building heightIndexMap (TreeMap)\nO(MN * (MN + 4MN)) -> running BFS to find shortest pathts between shortest and nextShortest tree.\nTime complexity of BFS is O(V + E) when Adjacency List is used.\nFor each tree we can have maximum of 4*MN edges and we are running BFS MN times, so it totales to O(MN * (MN + 4MN))\n```\nTme complexity is sum of the above, which can be simplified to O(MN * (MN + 4MN)) = O((MN)^2)\n\n**Bonus: the solution should work if input is not a matrix, but a `List<List<Integer>> forest` with random number of cells in each row**\n\n\n```\nclass Solution {\n Map<Integer, List<Integer>> adjucencyMap;\n Map<Integer, Integer> heightIndexMap;\n int forestSize = 0;\n \n public int cutOffTree(List<List<Integer>> forest) {\n if(forest.get(0).get(0) == 0){\n //(0,0) point is blocked\n return -1;\n }\n \n adjucencyMap = new HashMap<>(); \n //we use TreeMap so that trees will be sorted by height\n heightIndexMap = new TreeMap<>();\n forestSize = 0;\n \n for(int i = 0; i<forest.size(); i++){\n for(int j = 0; j<forest.get(i).size(); j++){ \n int cell = forest.get(i).get(j);\n int index = i*forest.get(i).size() + j + 1;\n //only consider trees we need to cut, ignore "1\'s"\n if(cell > 1){\n heightIndexMap.put(forest.get(i).get(j), index);\n }\n \n //only consider walkable cells\n if(cell > 0) {\n List<Integer> adjucent = new ArrayList<>();\n if(j-1 >= 0 && forest.get(i).get(j-1) > 0){\n //add left\n adjucent.add(index - 1); \n }\n if(j+1 < forest.get(i).size() && forest.get(i).get(j+1) > 0){\n //add right\n adjucent.add(index + 1); \n }\n if(i-1 >= 0 && j < forest.get(i-1).size() && forest.get(i-1).get(j) > 0){\n //add top\n adjucent.add(index - forest.get(i-1).size()); \n \n }\n if(i+1 < forest.size() && j < forest.get(i+1).size() && forest.get(i+1).get(j) > 0){\n //add bot\n adjucent.add(index + forest.get(i).size()); \n } \n adjucencyMap.put(index, adjucent); \n }\n \n forestSize++;\n }\n }\n \n int result = 0;\n int startIndex = 1;\n List<Integer> sortedTrees = new ArrayList(heightIndexMap.keySet());\n \n for(int i = 0; i < sortedTrees.size(); i++){\n int height = sortedTrees.get(i);\n int targetIndex = heightIndexMap.get(height);\n int dist = bfsFindDist(startIndex, targetIndex);\n if(dist == -1){\n return dist;\n }\n result += dist;\n startIndex = targetIndex;\n }\n \n return result;\n }\n \n // return: distance from startTreeIndex to targetTreeIndex\n // -1 if no path found\n int bfsFindDist(int startTreeIndex, int targetTreeIndex){\n if(startTreeIndex == targetTreeIndex){\n return 0;\n }\n \n List<Integer> distances = new ArrayList<>();\n for(int i = 0; i<=forestSize; i++){\n distances.add(i, -1);\n }\n \n List<Boolean> visited = new ArrayList<>();\n for(int i = 0; i<=forestSize; i++){\n visited.add(i, false);\n }\n \n visited.set(startTreeIndex, true);\n distances.set(startTreeIndex, 0); \n Queue<Integer> queue = new LinkedList<>();\n queue.add(startTreeIndex);\n while(!queue.isEmpty()){\n int tree = queue.remove();\n for(int adj : adjucencyMap.get(tree)){\n if(adj == targetTreeIndex){\n return distances.get(tree)+1;\n }\n if(!visited.get(adj)){\n queue.add(adj);\n visited.set(adj, true);\n distances.set(adj, distances.get(tree)+1);\n }\n }\n }\n \n return distances.get(targetTreeIndex);\n }\n}\n```
1
0
[]
0
cut-off-trees-for-golf-event
Simple BFS | Clean Code | C++
simple-bfs-clean-code-c-by-utkarsh-ysr0
\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n if(!forest.size() || !forest[0].size()) return 0;\n int n = fores
utkarsh___
NORMAL
2021-05-27T08:35:28.162230+00:00
2021-05-27T08:35:28.162259+00:00
250
false
```\nclass Solution {\npublic:\n int cutOffTree(vector<vector<int>>& forest) {\n if(!forest.size() || !forest[0].size()) return 0;\n int n = forest.size();\n int m = forest[0].size();\n vector<int> trace;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n trace.push_back(forest[i][j]);\n }\n }\n sort(trace.begin(),trace.end());\n int curI=0,curJ=0;\n int steps = 0;\n for(auto i:trace){\n if(i==0||i==1) continue;\n int ans = bfs(curI,curJ,forest,i,n,m);\n if(ans==-1) return -1;\n steps+=ans; \n }\n return steps;\n }\nprivate:\n int bfs(int &curi, int &curj,vector<vector<int>> &forest, int dest,int n, int m){\n if(forest[curi][curj]==dest) return 0;\n vector<vector<int>> visited(n,vector<int>(m,0));\n visited[curi][curj]=1;\n list<pair<pair<int,int>,int>> q; //i,j, steps\n q.push_back({{curi,curj},0});\n while(!q.empty()){\n \n int i = q.front().first.first;\n int j = q.front().first.second;\n int steps = q.front().second;\n q.pop_front();\n if(forest[i][j]==dest){\n forest[i][j]=1;\n curi=i, curj=j;\n return steps;\n }\n if(i+1<n && visited[i+1][j]==0 && forest[i+1][j]!=0){\n visited[i+1][j]=1;\n q.push_back({{i+1,j},steps+1});\n }\n if(j+1<m && visited[i][j+1]==0 && forest[i][j+1]!=0){\n visited[i][j+1]=1;\n q.push_back({{i,j+1},steps+1});\n }\n if(i-1>=0 && visited[i-1][j]==0 && forest[i-1][j]!=0){\n visited[i-1][j]=1;\n q.push_back({{i-1,j},steps+1});\n }\n if(j-1>=0 && visited[i][j-1]==0 && forest[i][j-1]!=0){\n visited[i][j-1]=1;\n q.push_back({{i,j-1},steps+1});\n }\n }\n return -1;\n }\n};\n```
1
0
[]
0
find-the-highest-altitude
✅Beats 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥
beats-100-c-java-python-beginner-friendl-yawk
Intuition:\nTo find the highest altitude, we need to calculate the cumulative sum of the altitude gains at each step. Starting from the initial altitude of 0, w
rahulvarma5297
NORMAL
2023-06-19T03:59:15.152377+00:00
2023-07-25T10:42:48.266258+00:00
24,156
false
# Intuition:\nTo find the highest altitude, we need to calculate the cumulative sum of the altitude gains at each step. Starting from the initial altitude of 0, we keep adding the gain at each step to the current altitude. The highest altitude reached during this process is the answer we are looking for.\n\n# Approach:\n1. Initialize two variables: `maxAltitude` and `currentAltitude` to keep track of the maximum altitude encountered so far and the current altitude, respectively. Set both variables to 0.\n2. Iterate over the `gain` vector, starting from the first element.\n3. At each step, update the `currentAltitude` by adding the gain of the current step.\n4. Compare the `currentAltitude` with the `maxAltitude`. If it is greater, update `maxAltitude` to the new value.\n5. Repeat steps 3-4 for all elements in the `gain` vector.\n6. Once the iteration is complete, `maxAltitude` will hold the highest altitude reached.\n7. Return the value of `maxAltitude` as the result.\n\nThis approach ensures that we keep track of the maximum altitude encountered during the traversal and avoids unnecessary modifications to the input vector. By iterating over the `gain` vector only once, the solution is efficient and provides the correct result.\n# Code\n\n```C++ []\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int maxAltitude = 0;\n int currentAltitude = 0;\n \n for (int i = 0; i < gain.size(); i++) {\n currentAltitude += gain[i];\n maxAltitude = max(maxAltitude, currentAltitude);\n }\n \n return maxAltitude;\n }\n};\n```\n```Java []\nclass Solution {\n public int largestAltitude(int[] gain) {\n int maxAltitude = 0;\n int currentAltitude = 0;\n \n for (int i = 0; i < gain.length; i++) {\n currentAltitude += gain[i];\n maxAltitude = Math.max(maxAltitude, currentAltitude);\n }\n \n return maxAltitude;\n }\n}\n```\n```Python3 []\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n maxAltitude = 0\n currentAltitude = 0\n \n for g in gain:\n currentAltitude += g\n maxAltitude = max(maxAltitude, currentAltitude)\n \n return maxAltitude\n```\n\n![CUTE_CAT.png](https://assets.leetcode.com/users/images/9d32a68c-a698-414f-b82f-e7ecc693f3eb_1687147131.7430437.png)\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\n
128
3
['Array', 'Prefix Sum', 'C++', 'Java', 'Python3']
13
find-the-highest-altitude
[Python3] 1-line
python3-1-line-by-lee215-0tu3
Python3\npy\n def largestAltitude(self, A):\n return max([0] + list(accumulate(A)))\n\nSuggested by @nikamir\npy\n def largestAltitude(self, A):\n
lee215
NORMAL
2021-01-23T16:09:23.205328+00:00
2021-01-23T17:42:48.789561+00:00
10,771
false
**Python3**\n```py\n def largestAltitude(self, A):\n return max([0] + list(accumulate(A)))\n```\nSuggested by @nikamir\n```py\n def largestAltitude(self, A):\n return max(0, max(accumulate(A)))\n```
74
6
[]
9
find-the-highest-altitude
JAVA || C++ || PYTHON || SELF EXPLANATORY
java-c-python-self-explanatory-by-rajat_-d472
CPP\n\nRuntime: 0 ms, faster than 100.00% of C++ online submissions\nMemory Usage: 8 MB, less than 100.00% of C++ online submissions\n\nclass Solution {\npublic
rajat_gupta_
NORMAL
2021-01-23T18:56:27.886144+00:00
2021-01-23T18:56:27.886196+00:00
12,446
false
# **CPP**\n\n**Runtime: 0 ms, faster than 100.00% of C++ online submissions\nMemory Usage: 8 MB, less than 100.00% of C++ online submissions**\n```\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int max_alt=0;\n int curr_alt=0;\n for(int i=0;i<gain.size();i++){\n curr_alt+=gain[i]; \n max_alt=max(curr_alt, max_alt);\n }\n return max_alt;\n }\n};\n\n//TC: O(n), SC: O(1)\n```\n\n# **JAVA**\n\n**Runtime: 0 ms, faster than 100.00% of Java online submissions\nMemory Usage: 36.4 MB, less than 100.00% of Java online submissions**\n```\nclass Solution {\n public int largestAltitude(int[] gain) {\n int max_alt=0;\n int curr_alt=0;\n for(int i=0;i<gain.length;i++){\n curr_alt+=gain[i]; \n max_alt=Math.max(curr_alt, max_alt);\n }\n return max_alt;\n }\n}\n\n//TC: O(n), SC: O(1)\n```\n\n# **PYTHON**\n**Runtime: 32 ms, faster than 100.00% of Python3 online submissions\nMemory Usage: 14.2 MB, less than 100.00% of Python3 online submissions**\n\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n curr_alt=0\n max_alt=0\n for i in range(0,len(gain)):\n curr_alt+=gain[i]\n max_alt=max(max_alt,curr_alt)\n return max_alt\n\t\t\n//TC: O(n), SC: O(1)\t\t\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n
54
6
['C', 'C++', 'Java', 'Python3']
10
find-the-highest-altitude
Runtime: 0 ms, faster than 100.00% of Java online submissions
runtime-0-ms-faster-than-10000-of-java-o-f26x
\nint max = 0; \n int sum = 0;\n for(int i=0;i<gain.length;i++){\n sum = sum + gain[i];\n if(sum>max)\n max=
nimishapundhir
NORMAL
2021-06-02T08:50:17.078663+00:00
2021-06-08T12:23:43.754605+00:00
3,419
false
```\nint max = 0; \n int sum = 0;\n for(int i=0;i<gain.length;i++){\n sum = sum + gain[i];\n if(sum>max)\n max=sum;\n }\n return max;\n```\n\n**Upvote** if it was helpful.
43
0
['Java']
6
find-the-highest-altitude
[C++] Easy to understand one pass solution (100% time and 100% space)
c-easy-to-understand-one-pass-solution-1-u3zh
\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int result = 0;\n int count = 0;\n \n for (int s : gain)
bhaviksheth
NORMAL
2021-01-23T16:08:22.968724+00:00
2021-01-23T16:08:22.968751+00:00
3,660
false
```\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int result = 0;\n int count = 0;\n \n for (int s : gain) {\n count += s;\n result = max(result, count);\n }\n \n return result;\n }\n};\n```
22
1
[]
2
find-the-highest-altitude
python3 explained accumulate solution
python3-explained-accumulate-solution-by-baok
\nfrom itertools import accumulate \n\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max(accumulate(gain, initial=0))\
lauvenhelz
NORMAL
2021-02-25T19:03:51.210862+00:00
2021-02-26T07:00:02.225218+00:00
1,961
false
```\nfrom itertools import accumulate \n\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max(accumulate(gain, initial=0))\n```\n\nIf gain = [-5,1,5,0,-7], accumulate by default construct the following: \n\n```accumulate([-5,1,5,0,-7]) --> [-5, -4, 1, 1, -6]```\n\n(-5) + 1 + 5 + 0 + (-7)\n\nEach element is added to the next, this sum becomes the element of the final list. Could be pictured as a table: \n\n```\n -5 = -5\n-5 + 1 = -4\n-4 + 5 = 1\n 1 + 0 = 1\n 1 + -7 = -6\n```\n\nThe second column is the original list [-5,1,5,0,-7], the third column is the final list [-5, -4, 1, 1, -6]. The first column is the result of the previous step.\n\nIf the "initial" parameter is not provided, the first element of the result will be the first element of the original iterator. Providing "initial" we set the first element of the result. In case of this problem, the first element should be 0, because a biker always starts from 0:\n\n```accumulate([-5,1,5,0,-7], initial=0) --> [0, -5, -4, 1, 1, -6]```\n\nIn the end just find maximum gain by max()
19
0
['Python3']
1
find-the-highest-altitude
Simple 1 liner in Python
simple-1-liner-in-python-by-tryingall-df9w
\n\n# Code\n\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max(accumulate([0]+gain))\n
tryingall
NORMAL
2023-06-19T02:51:40.771788+00:00
2023-06-19T02:51:40.771806+00:00
1,532
false
\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max(accumulate([0]+gain))\n```
12
0
['Python3']
0
find-the-highest-altitude
JavaScript less than 86.85% and faster than 91.23%
javascript-less-than-8685-and-faster-tha-natn
\nconst largestAltitude = gain => { \n let previous = 0;\n let biggest = 0;\n \n for (let i = 0; i < gain.length; i += 1) {\n previous +=
seredulichka
NORMAL
2022-08-25T21:15:22.006973+00:00
2022-08-25T21:15:22.007014+00:00
2,212
false
```\nconst largestAltitude = gain => { \n let previous = 0;\n let biggest = 0;\n \n for (let i = 0; i < gain.length; i += 1) {\n previous += gain[i];\n if (previous > biggest) biggest = previous;\n }\n \n return biggest;\n};\n```
12
0
['JavaScript']
1
find-the-highest-altitude
Beats 100% + Video of Prefix Sum| Java C++ Python
beats-100-video-of-prefix-sum-java-c-pyt-w1h2
Approach\nThe altitude at any given point = sum of all pervious points in array. Keep track of max to track ans.\n\n1. Initiate altitude = 0 and max = 0.\n2. fo
jeevankumar159
NORMAL
2023-06-19T03:20:41.734654+00:00
2023-06-19T03:20:41.734678+00:00
1,782
false
# Approach\nThe altitude at any given point = sum of all pervious points in array. Keep track of max to track ans.\n\n1. Initiate altitude = 0 and max = 0.\n2. for i in arr: altitude+= arr[i]\n3. max = Math.max(altitude, max) \n4. return max\n\n<iframe width="560" height="315" src="https://www.youtube.com/embed/_Kfiw07DulY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n public int largestAltitude(int[] gain) {\n int altitude = 0;\n int max = 0;\n for(int i: gain){\n altitude +=i;\n max = Math.max(altitude, max);\n }\n return max;\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int largestAltitude(std::vector<int>& gain) {\n int altitude = 0;\n int max = 0;\n for(int i : gain) {\n altitude += i;\n max = std::max(altitude, max);\n }\n return max;\n }\n};\n```\n\n```\nclass Solution:\n def largestAltitude(self, gain):\n altitude = 0\n max_altitude = 0\n for i in gain:\n altitude += i\n max_altitude = max(altitude, max_altitude)\n return max_altitude\n```
11
0
['C', 'Python', 'Java']
0
find-the-highest-altitude
🏆C++ || EASY Prefix Sum
c-easy-prefix-sum-by-chiikuu-08xr
Code\n\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int max_altitude = 0;\n int current = 0;\n for(auto i:gai
CHIIKUU
NORMAL
2023-06-19T03:11:40.480366+00:00
2023-06-19T03:11:40.480398+00:00
1,708
false
# Code\n```\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int max_altitude = 0;\n int current = 0;\n for(auto i:gain){\n current += i;\n max_altitude = max(max_altitude,current);\n }\n return max_altitude;\n }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/b18dcb20-35e3-4a10-8974-4f3e9f2aa718_1687143452.991606.jpeg)\n
11
0
['C++']
1
find-the-highest-altitude
Prefix_Sum.py
prefix_sumpy-by-jyot_150-5x6e
Approach\nPrefix Sum\n# Complexity\n- Time complexity:\n O(n)\n\n# Code\n\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n l=[0
jyot_150
NORMAL
2023-06-19T03:22:56.570347+00:00
2023-06-19T03:28:53.524067+00:00
1,877
false
# Approach\nPrefix Sum\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n l=[0]\n for i in range(len(gain)):l.append(l[i]+gain[i])\n return max(l)\n```\n![](https://i.redd.it/iwj7ej9xwdp91.jpg)
10
0
['Math', 'Prefix Sum', 'Python3']
1
find-the-highest-altitude
One Line Solution Python3
one-line-solution-python3-by-moazmar-rod2
\n\n# Code\n\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max([0] + [sum(gain[:i+1]) for i in range(len(gain))]) \
moazmar
NORMAL
2023-06-19T09:49:59.956113+00:00
2023-06-19T09:49:59.956148+00:00
108
false
\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max([0] + [sum(gain[:i+1]) for i in range(len(gain))]) \n\n\n```
8
0
['Python3']
0
find-the-highest-altitude
Python Elegant & Short | One-Line | Prefix Sum
python-elegant-short-one-line-prefix-sum-tgdi
Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n retu
Kyrylo-Ktl
NORMAL
2023-06-19T07:35:06.108787+00:00
2023-06-19T09:40:27.240684+00:00
1,883
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max(accumulate(gain, initial=0))\n```
8
0
['Prefix Sum', 'Python', 'Python3']
1
find-the-highest-altitude
24ms, Python (with comments)
24ms-python-with-comments-by-akshar-code-d8gc
If you found this post helpfull, please Upvote :)\n\nclass Solution(object):\n def largestAltitude(self, gain):\n """\n :type gain: List[int]\n
Akshar-code
NORMAL
2021-05-22T12:04:15.959156+00:00
2021-05-22T12:04:15.959181+00:00
1,655
false
If you found this post helpfull, please **Upvote** :)\n```\nclass Solution(object):\n def largestAltitude(self, gain):\n """\n :type gain: List[int]\n :rtype: int\n """\n\t\t#initialize a variable to store the end output\n result = 0\n\t\t#initialize a variable to keep track of the altitude at each iteration\n current_altitude=0\n\t\t#looping through each of the gains\n for g in gain:\n\t\t#updating the current altitude based on the gain\n current_altitude += g\n\t\t\t#if the current altitude is greater than the highest altitude recorded then assign it as the result. This done iteratively, allows us to find the highest altitude\n if current_altitude > result:\n result = current_altitude\n return result\n```\n![image](https://assets.leetcode.com/users/images/f7dd9ca2-d957-4b03-96e9-fb18c23cdb60_1621685013.6429558.png)\n\nPlease comment if you have any doubts or suggestions :)
8
0
['Python', 'Python3']
1
find-the-highest-altitude
Java | Simple math | Beats 100% | Clean code
java-simple-math-beats-100-clean-code-by-s3w3
Approach\n Describe your approach to solving the problem. \nKeep track of the altitude at given point by starting from 0 and adding the gain value at each point
judgementdey
NORMAL
2023-06-19T00:32:06.042139+00:00
2023-06-19T00:34:21.223598+00:00
2,843
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nKeep track of the altitude at given point by starting from `0` and adding the `gain` value at each point. Calculate the maximum altitude out of all the points.\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```\nclass Solution {\n public int largestAltitude(int[] gain) {\n int altitude = 0, max = 0;\n\n for (var g : gain) {\n altitude += g;\n max = Math.max(max, altitude);\n }\n return max;\n }\n}\n```\nIf you like my solution, please upvote it!
7
0
['Array', 'Java']
2
find-the-highest-altitude
C++/Python| One Line | Prefix Sum | One Pass | O(N)🔥
cpython-one-line-prefix-sum-one-pass-on-4yo08
Intuition\n Describe your first thoughts on how to solve this problem. \nStore the perfix sum int the array and return max elemnt in prefix array . But if all
Xahoor72
NORMAL
2023-02-01T11:32:21.781947+00:00
2023-02-01T11:33:29.332248+00:00
2,586
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStore the perfix sum int the array and return max elemnt in prefix array . But if all are negative so we have toreturn 0 . So return `max(0,max_elem);`\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPrefix Sum\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**C++**\n```\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n for(int i=1;i<gain.size();i++)gain[i]=gain[i-1]+gain[i];\n return max(0,*max_element(gain.begin(),gain.end()));\n }\n};\n```\n**Python**\n```\ndef largestAltitude(self, A):\n return max(0, max(accumulate(A)))\n\n```\n
7
0
['Array', 'Prefix Sum', 'C++']
1