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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
queens-that-can-attack-the-king | Java 1 ms Simple Implementation | java-1-ms-simple-implementation-by-sunny-6fwx | ```\n\tpublic List> queensAttacktheKing(int[][] queens, int[] king) {\n List> coordinates= new ArrayList>();\n boolean[][] chessBoard= new boolean | sunnydhotre | NORMAL | 2021-05-05T21:26:31.688076+00:00 | 2021-05-05T21:26:31.688106+00:00 | 99 | false | ```\n\tpublic List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> coordinates= new ArrayList<List<Integer>>();\n boolean[][] chessBoard= new boolean[8][8];\n for(int[] queenPos : queens){\n int x= queenPos[0], y= queenPos[1];\n chessBoard[x][y]= true;\n }\n int kx= king[0], ky= king[1];\n for(int i= kx-1; i>=0; i--){\n if(chessBoard[i][ky]){\n List<Integer> pos= Arrays.asList(i,ky);\n coordinates.add(pos);\n break;\n }\n }\n for(int i= kx+1; i<8; i++){\n if(chessBoard[i][ky]){\n List<Integer> pos= Arrays.asList(i,ky);\n coordinates.add(pos);\n break;\n }\n }\n for(int j= ky-1; j>=0; j--){\n if(chessBoard[kx][j]){\n List<Integer> pos= Arrays.asList(kx,j);\n coordinates.add(pos);\n break;\n }\n }\n for(int j= ky+1; j<8; j++){\n if(chessBoard[kx][j]){\n List<Integer> pos= Arrays.asList(kx,j);\n coordinates.add(pos);\n break;\n }\n }\n for(int i= kx-1, j= ky-1; i>=0 && j>=0; i--, j--){\n if(chessBoard[i][j]){\n List<Integer> pos= Arrays.asList(i,j);\n coordinates.add(pos);\n break;\n }\n }\n for(int i= kx-1, j= ky+1; i>=0 && j<8; i--, j++){\n if(chessBoard[i][j]){\n List<Integer> pos= Arrays.asList(i,j);\n coordinates.add(pos);\n break;\n }\n }\n for(int i= kx+1, j= ky+1; i<8 && j<8; i++, j++){\n if(chessBoard[i][j]){\n List<Integer> pos= Arrays.asList(i,j);\n coordinates.add(pos);\n break;\n }\n }\n for(int i= kx+1, j= ky-1; i<8 && j>=0; i++, j--){\n if(chessBoard[i][j]){\n List<Integer> pos= Arrays.asList(i,j);\n coordinates.add(pos);\n break;\n }\n }\n return coordinates;\n } | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | python 3 solution o(n) time, 2 loops | python-3-solution-on-time-2-loops-by-shu-ytin | \nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n hashTable = {\n "lu": [], | shubhbhardwaj | NORMAL | 2021-05-02T07:53:28.968524+00:00 | 2021-05-02T07:53:43.538144+00:00 | 139 | false | ```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n hashTable = {\n "lu": [],\n "uu": [],\n "ru": [],\n "rr": [],\n "rb": [],\n "bb": [],\n "lb": [],\n "ll": []\n }\n i,j = king\n for qi, qj in queens:\n #diagonal check\n if abs(qi-i) == abs(qj-j):\n # diagonal in upper half\n if qi < i:\n #diagonal in upper left quater\n if qj < j:\n #checking for minimum distance from king\n if hashTable[\'lu\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'lu\'])[0])+abs(j-(hashTable[\'lu\'])[1])):\n continue\n else:\n hashTable[\'lu\'] = [qi,qj]\n else:\n hashTable[\'lu\'] = [qi, qj]\n continue\n else:\n if hashTable[\'ru\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'ru\'])[0])+abs(j-(hashTable[\'ru\'])[1])):\n continue\n else:\n hashTable[\'ru\'] = [qi,qj]\n else:\n hashTable[\'ru\'] = [qi, qj]\n continue\n else:\n if qj < j:\n if hashTable[\'lb\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'lb\'])[0])+abs(j-(hashTable[\'lb\'])[1])):\n continue\n else:\n hashTable[\'lb\'] = [qi,qj]\n else:\n hashTable[\'lb\'] = [qi, qj]\n continue\n else:\n if hashTable[\'rb\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'rb\'])[0])+abs(j-(hashTable[\'rb\'])[1])):\n continue\n else:\n hashTable[\'rb\'] = [qi,qj]\n else:\n hashTable[\'rb\'] = [qi, qj]\n continue\n \n \n \n # horizontal check\n if qi == i:\n if qj < j:\n if hashTable[\'ll\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'ll\'])[0])+abs(j-(hashTable[\'ll\'])[1])):\n continue\n else:\n hashTable[\'ll\'] = [qi,qj]\n else:\n hashTable[\'ll\'] = [qi, qj]\n continue\n else:\n if hashTable[\'rr\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'rr\'])[0])+abs(j-(hashTable[\'rr\'])[1])):\n continue\n else:\n hashTable[\'rr\'] = [qi,qj]\n else:\n hashTable[\'rr\'] = [qi, qj]\n continue\n \n # vertical check\n if qj == j:\n if qi < i:\n if hashTable[\'uu\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'uu\'])[0])+abs(j-(hashTable[\'uu\'])[1])):\n continue\n else:\n hashTable[\'uu\'] = [qi,qj]\n else:\n hashTable[\'uu\'] = [qi, qj]\n continue\n else:\n if hashTable[\'bb\']:\n if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable[\'bb\'])[0])+abs(j-(hashTable[\'bb\'])[1])):\n continue\n else:\n hashTable[\'bb\'] = [qi,qj]\n else:\n hashTable[\'bb\'] = [qi, qj]\n continue\n ans= []\n for value in hashTable.values():\n if value:\n ans.append(value)\n return ans\n\t\t``` | 1 | 0 | ['Python', 'Python3'] | 0 |
queens-that-can-attack-the-king | 86.74% faster c++ sol | 8674-faster-c-sol-by-tjrandhawa26-mfn4 | ```\nclass Solution {\npublic:\n vector> queensAttacktheKing(vector>& queens, vector& king) \n {\n vector>ans;\n int i=king[0],j=king[1]-1; | Tjrandhawa26 | NORMAL | 2021-03-26T23:28:22.425808+00:00 | 2021-03-26T23:28:22.425844+00:00 | 49 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) \n {\n vector<vector<int>>ans;\n int i=king[0],j=king[1]-1;\n /*for left row */\n while(j>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n j--;\n \n }\n /* right row*/\n j=king[1]+1;\n while(j<8)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n \n }\n j++;\n }\n /*up column*/\n i=king[0]-1;\n j=king[1];\n while(i>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n i--;\n }\n \n /* down column*/\n i=king[0]+1;\n while(i<8)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n i++;\n }\n \n /*north west diagonal*/\n i=king[0]-1;\n j=king[1]-1;\n while(i>=0&&j>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n i--;\n j--;\n \n }\n \n /* north east diagonal*/\n \n i=king[0]-1;\n j=king[1]+1;\n while(i>=0&&j<8)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n i--;\n j++;\n \n }\n \n /* south west diagonal*/\n \n i=king[0]+1;\n j=king[1]-1; \n while(i<8&&j>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n i++;\n j--;\n \n }\n \n /* south east diagonal*/\n i=king[0]+1;\n j=king[1]+1;\n while(i<8&&j<8)\n {\n if(count(queens.begin(),queens.end(),vector<int>{i,j})==1)\n {\n ans.push_back(vector<int>{i,j});\n break;\n }\n i++;\n j++;\n \n }\n \n return ans;\n }\n}; | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | easy c++ code faster than 100 percent | easy-c-code-faster-than-100-percent-by-s-dqyq | class Solution {\npublic:\n vector> queensAttacktheKing(vector>& queens, vector& king) {\n int chess[8][8]={0};\n int i,j;\n int n=queen | shubhamsinhanitt | NORMAL | 2021-01-09T10:20:38.866475+00:00 | 2021-01-09T10:20:38.866507+00:00 | 61 | false | class Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n int chess[8][8]={0};\n int i,j;\n int n=queens.size();\n int x=king[0];\n int y=king[1];\n vector<vector<int>>res;\n chess[x][y]=1;\n for(i=0;i<n;i++)\n {\n x=queens[i][0];\n y=queens[i][1];\n chess[x][y]=2;\n }\n x=king[0];\n y=king[1];\n for(j=y;j<8;j++)\n {\n if(chess[x][j]==2)\n {\n res.push_back({x,j});\n break;\n }\n }\n for(j=y;j>=0;j--)\n {\n if(chess[x][j]==2)\n {\n res.push_back({x,j});\n break;\n }\n }\n for(i=x;i<8;i++)\n {\n if(chess[i][y]==2)\n {\n res.push_back({i,y});\n break;\n }\n }\n for(i=x;i>=0;i--)\n {\n if(chess[i][y]==2)\n {\n res.push_back({i,y});\n break;\n }\n }\n int tempx=x;\n int tempy=y;\n while(tempx<8&&tempy<8)\n {\n if(chess[tempx][tempy]==2)\n {\n res.push_back({tempx,tempy});\n break;\n }\n \n tempx++;\n tempy++;\n \n }\n tempx=x;\n tempy=y;\n while(tempx>=0&&tempy>=0)\n {\n if(chess[tempx][tempy]==2)\n {\n res.push_back({tempx,tempy});\n break;\n }\n \n tempx--;\n tempy--;\n \n }\n tempx=x;\n tempy=y;\n while(tempx>=0&&tempy<8)\n {\n if(chess[tempx][tempy]==2)\n {\n res.push_back({tempx,tempy});\n break;\n }\n \n tempx--;\n tempy++;\n }\n tempx=x;\n tempy=y;\n while(tempx<8&&tempy>=0)\n {\n if(chess[tempx][tempy]==2)\n {\n res.push_back({tempx,tempy});\n break;\n }\n \n tempx++;\n tempy--;\n }\n return res;\n \n \n \n \n }\n}; | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | Java Easy Approach [beats 100% | Recursive ]. Code is talking for itself | java-easy-approach-beats-100-recursive-c-71f5 | class Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int[][] board = new int[8][8];\n List<List<In | akezhr | NORMAL | 2021-01-02T09:01:20.276990+00:00 | 2021-01-02T09:01:20.277038+00:00 | 77 | false | ```class Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int[][] board = new int[8][8];\n List<List<Integer>> ans = new ArrayList();\n \n for (int[] pos : queens) {\n board[pos[0]][pos[1]] = 1;\n }\n \n // There are 8 types of dirs\n for (int i = 0; i < 8; i++) {\n dfs(board, king[0], king[1], i, ans);\n }\n \n return ans; \n }\n \n public void dfs(int[][] board, int row, int col, int dir, List<List<Integer>> ans) {\n if (row < 0 || col < 0 || row >= 8 || col >= 8) \n return;\n if (board[row][col] == 1) {\n List<Integer> pos = new ArrayList();\n pos.add(row);\n pos.add(col);\n ans.add(pos);\n return;\n }\n \n switch (dir) {\n case 0: \n dfs(board, row-1, col, dir, ans);\n break;\n case 1: \n dfs(board, row-1, col-1, dir, ans);\n break;\n case 2: \n dfs(board, row, col-1, dir, ans);\n break;\n case 3: \n dfs(board, row+1, col-1, dir, ans);\n break;\n case 4: \n dfs(board, row+1, col, dir, ans);\n break;\n case 5: \n dfs(board, row+1, col+1, dir, ans);\n break;\n case 6: \n dfs(board, row, col+1, dir, ans);\n break;\n case 7: \n dfs(board, row-1, col+1, dir, ans);\n break;\n }\n }\n}``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | C++ unordered_set | c-unordered_set-by-michelusa-tgwo | \nstore queens coordinates in an unordered_set and find first match (if any) from king, in 8 directions.\n```\nclass Solution {\n constexpr static int SIZE | michelusa | NORMAL | 2020-11-28T02:16:47.121054+00:00 | 2020-11-28T02:20:12.391588+00:00 | 141 | false | \nstore queens coordinates in an unordered_set and find first match (if any) from king, in 8 directions.\n```\nclass Solution {\n constexpr static int SIZE = 8;\n \n struct hasher {\n size_t operator() (const pair<int,int>& coords)const {\n return coords.first*8 + coords.second;\n }\n };\npublic:\n vector<vector<int>> queensAttacktheKing( vector<vector<int>>& queens, const vector<int>& king) const{\n unordered_set<pair<int,int>, hasher> queenZ;\n for ( auto&& coords: queens) {\n queenZ.insert( {coords[0], coords[1]});\n }\n \n vector<vector<int>> res;\n constexpr array<int,8> col = {-1,1,0,0, 1,-1,1,-1};\n constexpr array<int,8> row = {0, 0,-1,1,1,-1,-1,1};\n \n for (auto idx = 0; idx < col.size(); ++idx) {\n \n auto x = check(col[idx], row[idx], queenZ, king);\n if (!x.empty())\n res.push_back(move(x));\n }\n \n return res;\n }\n \n vector<int> check(const int cd,const int rd, const unordered_set<pair<int,int>, hasher> &queenZ , const vector<int>& king) const{\n auto r = king[0];\n auto c = king[1];\n \n while (0 <= r && r < SIZE && 0 <= c && c < SIZE) {\n if (queenZ.count({r, c}))\n return {r,c};\n r += rd;\n c += cd;\n \n \n }\n \n return {};\n }\n}; | 1 | 0 | ['C'] | 0 |
queens-that-can-attack-the-king | python3 | python3-by-bakerston-ctin | \ndef queensAttacktheKing(queens,king):\n\t\tfrom collections import defaultdict\n\t\ta=defaultdict(lambda: 8)\n\t\tfor x in queens:\n\t\t\tif x[0]==king[0] and | Bakerston | NORMAL | 2020-11-19T03:00:57.607515+00:00 | 2020-11-19T03:00:57.607544+00:00 | 96 | false | ```\ndef queensAttacktheKing(queens,king):\n\t\tfrom collections import defaultdict\n\t\ta=defaultdict(lambda: 8)\n\t\tfor x in queens:\n\t\t\tif x[0]==king[0] and x[1]>king[1]:\n\t\t\t\ta["N"]=min(a["N"],x[1]-king[1])\n\t\telif x[0]==king[0] and x[1]<king[1]:\n\t\t\ta["S"]=min(a["S"],king[1]-x[1])\n\t\telif x[1]==king[1] and x[0]>king[0]:\n\t\t\ta["E"]=min(a["E"],x[0]-king[0]) \n\t\telif x[1]==king[1] and x[0]<king[0]:\n\t\t\ta["W"]=min(a["W"],king[0]-x[0])\n\t\telif x[1]-king[1]==x[0]-king[0] and x[1]>king[1]:\n\t\t\ta["NE"]=min(a["NE"],x[0]-king[0]) \n\t\telif x[1]-king[1]==x[0]-king[0] and x[1]<king[1]:\n\t\t\ta["SW"]=min(a["SW"],king[0]-x[0]) \n\t\telif x[1]-king[1]==-x[0]+king[0] and x[1]>king[1]:\n\t\t\ta["NW"]=min(a["NW"],x[1]-king[1])\n\t\telif x[1]-king[1]==-x[0]+king[0] and x[1]<king[1]:\n\t\t\ta["SE"]=min(a["SE"],x[0]-king[0])\n\t\telse:\n\t\t\tcontinue\n\tans=[] \n\tfor x in a.keys():\n\t\ttmp=[king[0],king[1]]\n\t\tif a[x]<8:\n\t\t\tif x=="N":\n\t\t\t\ttmp[1]+=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telif x=="S":\n\t\t\t\ttmp[1]-=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telif x=="W":\n\t\t\t\ttmp[0]-=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telif x=="E":\n\t\t\t\ttmp[0]+=a[x]\n\t\t\t\tans.append(tmp) \n\t\t\telif x=="NE":\n\t\t\t\ttmp[0]+=a[x]\n\t\t\t\ttmp[1]+=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telif x=="NW":\n\t\t\t\ttmp[0]-=a[x]\n\t\t\t\ttmp[1]+=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telif x=="SE":\n\t\t\t\ttmp[0]+=a[x]\n\t\t\t\ttmp[1]-=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telif x=="SW":\n\t\t\t\ttmp[0]-=a[x]\n\t\t\t\ttmp[1]-=a[x]\n\t\t\t\tans.append(tmp)\n\t\t\telse:\n\t\t\t\tcontinue \n\treturn ans\n\t``` | 1 | 0 | [] | 0 |
find-minimum-time-to-reach-last-room-ii | Easy & Clear Solution (Java, c++, Python3) | easy-clear-solution-java-c-python3-by-mo-xb2n | \n\n### Problem Explanation\n\nIn this problem, you are navigating through a dungeon represented by a grid of rooms. Each room has a specified minimum time (mov | moazmar | NORMAL | 2024-11-03T04:15:31.630359+00:00 | 2024-11-03T04:49:04.180256+00:00 | 1,597 | false | \n\n### Problem Explanation\n\nIn this problem, you are navigating through a dungeon represented by a grid of rooms. Each room has a specified minimum time (`moveTime[i][j]`) indicating when you can start moving into that room. You begin at the top-left room `(0, 0)` at time `t = 0` and aim to reach the bottom-right room `(n - 1, m - 1)`. Moving between adjacent rooms takes alternating amounts of time\u20141 second for the first move and 2 seconds for the next move, and this alternation continues.\n\nTo solve this problem, we use a priority queue to explore rooms based on the minimum time to reach them. We keep track of the minimum time required to enter each room and update our path accordingly.\n\n### Python Implementation\n\nHere\u2019s the Python implementation of the solution with meaningful variable names:\n\n```python\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n # Store the input moveTime in a variable named roomMoveTime\n roomMoveTime = moveTime \n totalRows = len(roomMoveTime)\n totalCols = len(roomMoveTime[0])\n \n # Priority queue to store (current_time, row, col, step_cost)\n priorityQueue = [(0, 0, 0, 1)] # Start at (0, 0) with time 0 and step cost 1\n minimumArrivalTime = [[float(\'inf\')] * totalCols for _ in range(totalRows)]\n minimumArrivalTime[0][0] = 0\n\n # Directions for adjacent rooms (down, up, right, left)\n adjacentDirections = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n while priorityQueue:\n currentTime, currentRow, currentCol, currentStepCost = heapq.heappop(priorityQueue)\n\n # If we reached the target room (totalRows - 1, totalCols - 1)\n if (currentRow, currentCol) == (totalRows - 1, totalCols - 1):\n return currentTime\n\n # Explore adjacent rooms\n for dx, dy in adjacentDirections:\n nextRow, nextCol = currentRow + dx, currentCol + dy\n\n if 0 <= nextRow < totalRows and 0 <= nextCol < totalCols:\n waitTime = max(roomMoveTime[nextRow][nextCol] - currentTime, 0)\n newArrivalTime = currentTime + currentStepCost + waitTime\n\n # Only push to the queue if we found a better arrival time\n if newArrivalTime < minimumArrivalTime[nextRow][nextCol]:\n minimumArrivalTime[nextRow][nextCol] = newArrivalTime\n nextStepCost = 1 if currentStepCost == 2 else 2\n heapq.heappush(priorityQueue, (newArrivalTime, nextRow, nextCol, nextStepCost))\n\n return -1 # Return -1 if the target room is unreachable\n```\n\n### C++ Implementation\n\nHere\u2019s the C++ implementation with clear variable names:\n\n```cpp\nclass Solution {\npublic:\n int minTimeToReach(std::vector<std::vector<int>>& moveTime) {\n // Store the input moveTime in a variable named roomMoveTime\n std::vector<std::vector<int>> roomMoveTime = moveTime; \n int totalRows = roomMoveTime.size();\n int totalCols = roomMoveTime[0].size();\n \n // Priority queue to store (current_time, row, col, step_cost)\n using State = std::tuple<int, int, int, int>; // (current_time, row, col, step_cost)\n std::priority_queue<State, std::vector<State>, std::greater<State>> priorityQueue;\n priorityQueue.emplace(0, 0, 0, 1); // Start at (0, 0) with time 0 and step cost 1\n \n std::vector<std::vector<int>> minimumArrivalTime(totalRows, std::vector<int>(totalCols, INT_MAX));\n minimumArrivalTime[0][0] = 0;\n\n // Directions for adjacent rooms (down, up, right, left)\n std::vector<std::pair<int, int>> adjacentDirections = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n\n while (!priorityQueue.empty()) {\n auto [currentTime, currentRow, currentCol, currentStepCost] = priorityQueue.top();\n priorityQueue.pop();\n\n // If we reached the target room (totalRows - 1, totalCols - 1)\n if (currentRow == totalRows - 1 && currentCol == totalCols - 1) {\n return currentTime;\n }\n\n // Explore adjacent rooms\n for (const auto& [dx, dy] : adjacentDirections) {\n int nextRow = currentRow + dx;\n int nextCol = currentCol + dy;\n\n if (nextRow >= 0 && nextRow < totalRows && nextCol >= 0 && nextCol < totalCols) {\n int waitTime = std::max(roomMoveTime[nextRow][nextCol] - currentTime, 0);\n int newArrivalTime = currentTime + currentStepCost + waitTime;\n\n // Only push to the queue if we found a better arrival time\n if (newArrivalTime < minimumArrivalTime[nextRow][nextCol]) {\n minimumArrivalTime[nextRow][nextCol] = newArrivalTime;\n int nextStepCost = (currentStepCost == 2) ? 1 : 2;\n priorityQueue.emplace(newArrivalTime, nextRow, nextCol, nextStepCost);\n }\n }\n }\n }\n\n return -1; // Return -1 if the target room is unreachable\n }\n};\n```\n\n### Java Implementation\n\nAnd here\u2019s the Java implementation with clear variable names:\n\n```java\n\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n // Store the input moveTime in a variable named roomMoveTime\n int[][] roomMoveTime = moveTime; \n int totalRows = roomMoveTime.length;\n int totalCols = roomMoveTime[0].length;\n\n // Priority queue to store (current_time, row, col, step_cost)\n PriorityQueue<int[]> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n priorityQueue.offer(new int[]{0, 0, 0, 1}); // Start at (0, 0) with time 0 and step cost 1\n \n int[][] minimumArrivalTime = new int[totalRows][totalCols];\n for (int[] row : minimumArrivalTime) {\n Arrays.fill(row, Integer.MAX_VALUE);\n }\n minimumArrivalTime[0][0] = 0;\n\n // Directions for adjacent rooms (down, up, right, left)\n int[][] adjacentDirections = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n\n while (!priorityQueue.isEmpty()) {\n int[] currentState = priorityQueue.poll();\n int currentTime = currentState[0], currentRow = currentState[1], currentCol = currentState[2], currentStepCost = currentState[3];\n\n // If we reached the target room (totalRows - 1, totalCols - 1)\n if (currentRow == totalRows - 1 && currentCol == totalCols - 1) {\n return currentTime;\n }\n\n // Explore adjacent rooms\n for (int[] direction : adjacentDirections) {\n int nextRow = currentRow + direction[0];\n int nextCol = currentCol + direction[1];\n\n if (nextRow >= 0 && nextRow < totalRows && nextCol >= 0 && nextCol < totalCols) {\n int waitTime = Math.max(roomMoveTime[nextRow][nextCol] - currentTime, 0);\n int newArrivalTime = currentTime + currentStepCost + waitTime;\n\n // Only push to the queue if we found a better arrival time\n if (newArrivalTime < minimumArrivalTime[nextRow][nextCol]) {\n minimumArrivalTime[nextRow][nextCol] = newArrivalTime;\n int nextStepCost = (currentStepCost == 2) ? 1 : 2;\n priorityQueue.offer(new int[]{newArrivalTime, nextRow, nextCol, nextStepCost});\n }\n }\n }\n }\n\n return -1; // Return -1 if the target room is unreachable\n }\n}\n```\n | 18 | 3 | ['C++', 'Java', 'Python3'] | 3 |
find-minimum-time-to-reach-last-room-ii | Python3 || 13 lines, heap and toggle || | python3-13-lines-heap-and-toggle-by-spau-98ho | Pretty much the same as the preceding problem, with the added feature that the step toggles between 1 and 2, which we achieve by replacing step with 3 - step.\ | Spaulding_ | NORMAL | 2024-11-03T22:16:23.360426+00:00 | 2024-11-12T17:09:16.189217+00:00 | 437 | false | Pretty much the same as the preceding problem, with the added feature that the step toggles between 1 and 2, which we achieve by replacing `step` with `3 - step`.\n\n```python3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n \n onGrid = lambda x, y: 0 <= x < n and 0 <= y < m\n n, m, dx, dy = len(moveTime), len(moveTime[0]), 1, 0\n heap = [(0, 0, 0, 1)]\n seen = {(0,0)}\n\n while heap:\n time, x, y, step = heappop(heap)\n\n if (x, y) == (n - 1, m - 1): return time\n\n for _ in range(4):\n\n X, Y, dx, dy = x + dx, y + dy, -dy, dx\n\n if onGrid(X, Y) and (X, Y) not in seen:\n t = max(time, moveTime[X][Y]) + step\n heappush(heap, [t, X, Y, 3 - step])\n seen.add((X, Y))\n```\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size(), m = moveTime[0].size();\n auto onGrid = [&](int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; };\n \n int dx = 1, dy = 0;\n priority_queue<tuple<int, int, int, int>, vector<tuple<int, int, int, int>>, greater<>> heap;\n heap.emplace(0, 0, 0, 1);\n\n set<pair<int, int>> seen;\n seen.emplace(0, 0);\n\n while (!heap.empty()) {\n auto [time, x, y, step] = heap.top();\n heap.pop();\n\n if (x == n - 1 && y == m - 1) return time;\n\n for (int i = 0; i < 4; ++i) {\n int X = x + dx, Y = y + dy;\n int temp_dx = dx, temp_dy = dy;\n dx = -temp_dy;\n dy = temp_dx;\n\n if (onGrid(X, Y) && !seen.count({X, Y})) {\n int t = max(time, moveTime[X][Y]) + step;\n heap.emplace(t, X, Y, 3 - step);\n seen.emplace(X, Y);}\n }\n }\n return -1;\n }\n};\n\n```\n```java []\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n int n = moveTime.length, m = moveTime[0].length;\n int dx = 1, dy = 0;\n\n PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n heap.add(new int[]{0, 0, 0, 1});\n\n Set<String> seen = new HashSet<>();\n seen.add("0,0");\n\n while (!heap.isEmpty()) {\n int[] current = heap.poll();\n int time = current[0], x = current[1], y = current[2], step = current[3];\n\n if (x == n - 1 && y == m - 1) return time;\n\n for (int i = 0; i < 4; i++) {\n int X = x + dx, Y = y + dy;\n int tempDx = dx, tempDy = dy;\n dx = -tempDy;\n dy = tempDx;\n\n String pos = X + "," + Y;\n if (onGrid(X, Y, n, m) && !seen.contains(pos)) {\n int t = Math.max(time, moveTime[X][Y]) + step;\n heap.add(new int[]{t, X, Y, 3 - step});\n seen.add(pos);}\n }\n }\n return -1; // Return -1 if unreachable\n }\n private boolean onGrid(int x, int y, int n, int m) {\n return 0 <= x && x < n && 0 <= y && y < m;\n }\n}\n\n```\n[https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii/submissions/1442140920/](https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii/submissions/1442140920/)\n\nI could be wrong, but I think that time complexity is *O*(*N* log *N*) and space complexity is *O*(*N*), in which *N* ~ `m * n` . | 16 | 0 | ['C++', 'Java', 'Python3'] | 2 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkstra's Algorithm | modified-dijkstras-algorithm-by-donpaul2-jvud | Use a priority queue containing a tuple of size 4.1st element in the tuple denotes time taken to reach that cell (negetive to maintain min heap)
2nd and 3rd are | donpaul271 | NORMAL | 2024-11-03T04:35:19.539972+00:00 | 2025-03-03T01:50:47.700543+00:00 | 2,464 | false |
Use a priority queue containing a tuple of size 4.
1st element in the tuple denotes time taken to reach that cell (negetive to maintain min heap)
2nd and 3rd are the x and y axis.
4th element denotes the decision variable dec.
when dec is 0 it implies it takes 1 second to move
when dec is 1 it implies it takes 2 second to move.
Toggle the decision variable everytime we push new element to priority queue.
Run a dijkstras algo with this setup while moving up, down left, right.
(please upvote if it helped)
# Code
```cpp []
#define ll long long
vector<ll> xm{+1, -1, 0, 0};
vector<ll> ym{0, 0, +1, -1};
class Solution {
public:
int minTimeToReach(vector<vector<int>>& g) {
priority_queue<tuple<ll, ll, ll, ll>> pq;
ll n = g.size();
ll m = g[0].size();
vector<ll> t(m, 1e15);
vector<vector<ll>> dist(n, t);
pq.push({0, 0, 0, 0}); // initially dec = 0 as time to move = 1.
dist[0][0] = 0;
ll ans, ex, nx;
while(!pq.empty())
{
ll d = -get<0>(pq.top()); // take negetive to get the actual value. While pushing we use negetive sign to maintain min heap.
ll x = get<1>(pq.top());
ll y = get<2>(pq.top());
ll dec = get<3>(pq.top());
pq.pop();
if(dec == 0) // if dec == 0 next value of dec = 1 and extra time = 1
{
nx = 1;
ex = 1;
}
else // if dec == 1 next value of dec = 0 and extra time = 2
{
nx = 0;
ex = 2;
}
if(dist[x][y] < d) // not useful to proceed if current d is greater than least d possible.
continue;
if(x == n-1 && y == m-1) // break when the target cell is found.
{
ans = d;
break;
}
for(int i=0; i<4; ++i) // checking top, down, left, right.
{
ll xn = x + xm[i];
ll yn = y + ym[i];
if(xn >=0 && xn < n && yn>=0 && yn < m)
{
ll a = g[xn][yn];
ll now = max(d+ex, a+ex); // adding time required to move ex.
if(dist[xn][yn] > now)
{
dist[xn][yn] = now;
pq.push({-now, xn, yn, nx}); // push negetive value of now to convert default max heap to min heap and push toggled dec variable nx.
}
}
}
}
return ans;
}
};
``` | 15 | 0 | ['C++'] | 2 |
find-minimum-time-to-reach-last-room-ii | [Java/C++/Python] Priority Queue | javacpython-priority-queue-by-lee215-f188 | Intuition\nUse priority queue.\n\n\n# Explanation\nThe key is [t, c, i, j],\nwhere it takes t seconds to arrive (i, j),\nthe next move will cost c seconds.\n\nU | lee215 | NORMAL | 2024-11-03T04:13:35.207550+00:00 | 2024-11-04T03:15:10.499580+00:00 | 952 | false | # **Intuition**\nUse priority queue.\n<br>\n\n# **Explanation**\nThe key is `[t, c, i, j]`,\nwhere it takes `t` seconds to arrive `(i, j)`,\nthe next move will cost `c` seconds.\n\nUse `3 - d` to determine the next cost of move.\n<br>\n\n# **Complexity**\nTime `O(mnlogmn)`\nSpace `O(mn)`\n<br>\n\n```Java [Java]\n public int minTimeToReach(int[][] A) {\n int n = A.length, m = A[0].length, inf = Integer.MAX_VALUE;\n int[][] dp = new int[n][m];\n for (int i = 0; i < n; i++) {\n Arrays.fill(dp[i], inf);\n }\n PriorityQueue<int[]> h = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n h.offer(new int[]{0, 0, 0}); // arrive time, i, j\n A[0][0] = -1;\n\n while (!h.isEmpty()) {\n int[] cur = h.poll();\n int t = cur[0], i = cur[1], j = cur[2];\n if (t >= dp[i][j]) continue;\n if (i == n - 1 && j == m - 1) return t;\n dp[i][j] = t;\n\n int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n for (int[] dir : dirs) {\n int x = i + dir[0], y = j + dir[1], c = (i + j) % 2 + 1;\n if (0 <= x && x < n && 0 <= y && y < m && dp[x][y] == inf) {\n h.offer(new int[]{Math.max(A[x][y], t) + c, x, y});\n }\n }\n }\n return -1;\n }\n```\n\n```C++ [C++]\n int minTimeToReach(vector<vector<int>>& A) {\n int n = A.size(), m = A[0].size(), inf = INT_MAX;\n vector<vector<int>> dp(n, vector<int>(m, inf));\n priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> h;\n h.push({0, 0, 0}); // arrive time, i, j\n A[0][0] = -1;\n\n vector<vector<int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n while (!h.empty()) {\n vector<int> cur = h.top();\n h.pop();\n int t = cur[0], i = cur[1], j = cur[2];\n if (t >= dp[i][j]) continue;\n if (i == n - 1 && j == m - 1) return t;\n dp[i][j] = t;\n\n for (auto& dir : dirs) {\n int x = i + dir[0], y = j + dir[1], c = (i + j) % 2 + 1;\n if (0 <= x && x < n && 0 <= y && y < m && dp[x][y] == inf) {\n h.push({max(A[x][y], t) + c, x, y});\n }\n }\n }\n return -1;\n }\n```\n\n```py [Python3]\n def minTimeToReach(self, A: List[List[int]]) -> int:\n n, m = len(A), len(A[0])\n dp = [[inf] * m for i in range(n)]\n h = [[0, 0, 0]] # arrive time, i, j\n A[0][0] = -1\n while h:\n t, i, j = heappop(h)\n if t >= dp[i][j]: continue\n if i == n - 1 and j == m - 1: return t\n dp[i][j] = t\n for di, dj in [[1, 0], [0, 1], [-1, 0], [0, -1]]:\n x, y = i + di, j + dj\n c = (i + j) % 2 + 1\n if 0 <= x < n and 0 <= y < m and dp[x][y] == inf:\n heappush(h, [max(A[x][y], t) + c, x, y])\n```\n | 9 | 0 | [] | 3 |
find-minimum-time-to-reach-last-room-ii | Easiest Solution 🔥✅ | Modified Dijkstra's | easiest-solution-modified-dijkstras-by-1-53qz | Approach\nExactly the same as:\nhttps://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/solutions/6000113/easiest-solution-heap-bfs/\nOnly differen | 1AFN19tfV2 | NORMAL | 2024-11-03T04:01:18.748178+00:00 | 2024-11-04T16:58:04.200094+00:00 | 802 | false | # Approach\nExactly the same as:\nhttps://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/solutions/6000113/easiest-solution-heap-bfs/\nOnly difference is we add a new value `check` into the heap which we will use to check if we need to add 1 or 2 to the current time. This change is made when we push again into the heap.\n\n# Complexity\n- Time complexity: $$O(m*nlog(m*n))$$, where m and n are grid dimensions.\n\n- Space complexity: $$O(m*n)$$, for the heap and visited set.\n\n# Code\n```python3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m, n = len(moveTime) - 1, len(moveTime[0]) - 1\n heap = [(0, 0, 0, True)]\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n visited = set()\n while heap:\n time, r, c, check = heapq.heappop(heap)\n if (r, c) == (m, n): return time\n new = 1 if check else 2\n for x, y in directions:\n row, col = x + r, y + c\n if row <= m and col <= n and col >= 0 and row >= 0 and (row, col) not in visited:\n heapq.heappush(heap, (max(time, moveTime[row][col]) + new, row, col, not check))\n visited.add((row, col))\n```\n```cpp []\n#include <vector>\n#include <queue>\n#include <tuple>\n#include <set>\nusing namespace std;\n\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m = moveTime.size() - 1, n = moveTime[0].size() - 1;\n priority_queue<tuple<int, int, int, bool>, vector<tuple<int, int, int, bool>>, greater<>> heap;\n heap.push({0, 0, 0, true});\n vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n set<pair<int, int>> visited;\n while (!heap.empty()) {\n auto [time, r, c, check] = heap.top();\n heap.pop();\n if (r == m && c == n) return time;\n int newTime = check ? 1 : 2;\n for (auto& dir : directions) {\n int row = r + dir[0], col = c + dir[1];\n if (row <= m && col <= n && row >= 0 && col >= 0 && !visited.count({row, col})) {\n heap.push({max(time, moveTime[row][col]) + newTime, row, col, !check});\n visited.insert({row, col});\n }\n }\n }\n return -1;\n }\n};\n```\n```java []\nimport java.util.*;\n\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n int m = moveTime.length - 1, n = moveTime[0].length - 1;\n PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n heap.offer(new int[]{0, 0, 0, 1});\n int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n Set<String> visited = new HashSet<>();\n while (!heap.isEmpty()) {\n int[] curr = heap.poll();\n int time = curr[0], r = curr[1], c = curr[2], check = curr[3];\n if (r == m && c == n) return time;\n int newTime = check == 1 ? 1 : 2;\n for (int[] dir : directions) {\n int row = r + dir[0], col = c + dir[1];\n if (row <= m && col <= n && row >= 0 && col >= 0 && !visited.contains(row + "," + col)) {\n heap.offer(new int[]{Math.max(time, moveTime[row][col]) + newTime, row, col, 1 - check});\n visited.add(row + "," + col);\n }\n }\n }\n return -1;\n }\n}\n\n``` | 6 | 0 | ['Heap (Priority Queue)', 'Shortest Path', 'C++', 'Java', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Detailed Dry-Run Approach | detailed-dry-run-approach-by-mainframeku-rxdd | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires us to navigate through a grid of rooms, each with a designated tim | MainFrameKuznetSov | NORMAL | 2024-11-03T07:08:19.331345+00:00 | 2024-11-03T07:08:19.331368+00:00 | 80 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to navigate through a grid of rooms, each with a designated time that must pass before we can move into it.To solve this, the use of a graph traversal algorithm is necessary since the solution involves finding the shortest path in terms of time.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Declaration\n - Create a priority queue(Min-Heap) to store rooms as we explore them, initialized with the starting room (0,0) at time 0 with a count of 0.\n - Maintain a temp array to track the minimum time required to reach each room. temp[0][0] is initialised to zero since we start here and time taken to reach this is 0 seconds. Others can be initialised with a high value(here INT_MAX is taken).\n \n- Path Exploration\n - While the priority queue is not empty, pop the room currently with the minimum accumulated time.\n - For each room, check its four possible neighbors (up, down, left, right).[for (i,j) the possible paths are:- (i+1,j),(i-1,j),(i,j+1),(i-j-1)]\n - Calculate the waiting time to enter each neighbor based on the current time and the room\'s entry time(here 1 second or seconds[flipping simultaneously]).\n - If this new time is less than the previously recorded time for that neighbor, update the time and push the neighbor into the priority queue.\n - While undergoing such transitions for path finding, if we encounter (n-1,m-1) we return the current time curr.\n - After the whole min-heap is processed, we check if nothing has been returned, we return \u22121(disconnected component)\n\n# Example\n\ngrid=[[0,2],[1,4]]\n\n- Declaration\n - We start at room (0,0) at time 0.\n - The priority queue is initialized with pq={0,{0,0}}.\n - The temp array is initialized as:- [[0,INT_MAX],[INT_MAX,INT_MAX]]\n \n- Path Exploration \n - 1st iteration\n - Pop the element from the queue: $curr=0$, $(x,y)=(0,0)$,$cnt=0$.\n - Check if we\'ve reached the target (1,1).[False]\n - Explore neighbors:-\n - $Right(0,1)$:-\n - New time calculation:$add=(cnt?2:1)=1$, $wait=max(0,2)+1=3$.\n - Since 3<INT_MAX, update $temp[0][1]$ $to$ $3$ and push to heap.\n - temp=[[0,3],[INT_MAX,INT_MAX]]\n - pq={3,{0,1,1}}\n - $Down(1,0)$:-\n - New time calculation:$add=(cnt?2:1)=1$,$wait=max(0,1)+1=2$\n - Since 2<INT_MAX, update $temp[1][0]$ $to$ $2$ and push to heap.\n - temp=[[0,3],[2,INT_MAX]]\n - pq={{2,{1,0,1}},{3,{0,1,1}}} \n - $Up$ and $Left$ are out of bounds. \n \n - 2nd Interation\n - Pop the element from the queue: $curr=2$,$(x,y)=(1,0)$,$cnt=1$.\n - Check if we\'ve reached the target (1,1): [False]\n - Explore neighbors:\n - $Up(0,0)$:\n - Already visited with temp[0][0]=0, so we skip.\n - $Down(1,1)$:\n - New time calculation:$add=(cnt?2:1)=2$,$wait=max(2,4)+2=6$.\n - Since 5<INT_MAX, update $temp[1][1$] $to$ $5$ and push to heap.\n - temp=[[0,3],[2,6]]\n - pq={{3,{0,1,1}},{6,{1,1,0}}}\n - $Left$ out of bounds.\n - $Right(1,1)$ already computed. \n\n - 3rd Iteration\n - Pop the element from the queue: $curr=3$, $(x,y)=(0,1)$,$cnt=1$.\n - Check if we\'ve reached the target (1,1): [False]\n - Explore neighbors:\n - $Up$: Out of bounds, so we skip.\n - $Down(1,1)$:\n - New time calculation:$add=(cnt?2:1)=2$,wait=max(3,4)+2=6.\n - Since 6>=temp[1][1], we skip.\n - temp=[[0,3],[2,6]]\n - pq={{6,{1,1,0}}}\n - $Left(0,0)$:Already computed\n - $Right(0,2)$:Out of bounds\n \n - 4th Iteration\n - Pop the element from the queue: $curr=6$,$(x,y)=(1,1)$.\n - Check if we\'ve reached the target (1,1):[True]\n - Return:- $curr=6$.\n\n\n\n# Complexity\n- Time complexity:-$O(n*m*log(n*m))$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:-$O(n*m)+O(n*m)$ One for storing the $temp$ array and other for the $priority$ $queue$(Worst Case)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>&grid) {\n int n=grid.size(),m=grid[0].size();\n vector<pair<int,int>>dir={{0,1},{1,0},{0,-1},{-1,0}};\n \n //int cnt=0;\n priority_queue<pair<int,vector<int>>,vector<pair<int,vector<int>>>,greater<pair<int,vector<int>>>>pq;\n pq.push({0,{0,0,0}});\n\n vector<vector<int>>temp(n,vector<int>(m,INT_MAX));\n temp[0][0]=0;\n while(!pq.empty())\n {\n auto it=pq.top();\n pq.pop();\n int curr=it.first;\n int x=it.second[0],y=it.second[1],cnt=it.second[2];\n if(x==n-1 && y==m-1)\n return curr;\n for(int i=0;i<4;++i)\n {\n int nx=x+dir[i].first;\n int ny=y+dir[i].second;\n if(nx>=0 && nx<n && ny>=0 && ny<m)\n {\n int add=(cnt)?2:1;\n int wait=max(curr,grid[nx][ny])+add;\n if(wait<temp[nx][ny])\n {\n temp[nx][ny]=wait;\n pq.push({wait,{nx,ny,1-cnt}});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 5 | 0 | ['Graph', 'Heap (Priority Queue)', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | [Python3/C++/Java] Dijkstra - Detailed Solution | python3cjava-dijkstra-detailed-solution-nb4rf | Intuition\n Describe your first thoughts on how to solve this problem. \n- Shortest Path with a lot of constraints and conditions\n- All parameters are posivite | dolong2110 | NORMAL | 2024-11-16T12:46:56.467631+00:00 | 2024-11-16T12:51:56.081314+00:00 | 128 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Shortest Path with a lot of constraints and conditions\n- All parameters are posivite\n- It is the signal of Dijkstra or BFS\n- Each going path has its own weight. Thus Dijkstra\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Problem Understanding**\n\n- `moveTime`: A 2D list representing a grid. Each cell `moveTime[i][j]` holds the time it takes to move into that cell.\n- The goal is to start at the top-left corner `(0, 0)` and reach the bottom-right corner `(m-1, n-1)` in the minimum possible time.\n- There\'s a catch: after moving into a cell with a move time of `1`, the next move takes 2 units of time, and the next of next move takes 2 unit of times, and so on.\n\n**Code Explanation**\n\n**1. Initialization**:\n\n - `m, n = len(moveTime), len(moveTime[0])`: Get the dimensions of the grid.\n- `min_time`: A 2D list to store the minimum time to reach each cell. Initialized with infinity `float("inf")` for all cells except the starting cell `(0, 0)`, which is set to `0`.\n- `pq`: A priority queue (using `heapq`) to store tuples of `(current_time, i, j, move_time)`. This queue helps explore the grid efficiently by prioritizing cells with shorter travel times. It\'s initialized with the starting cell.\n\n**2. Dijkstra\'s Algorithm with a Twist**:\n\n- The code essentially uses a modified Dijkstra\'s algorithm. It iteratively explores the grid, expanding from the cell with the current minimum time.\n- `while pq:`: The loop continues as long as there are cells to explore in the priority queue.\n - `cur_time, i, j, move_time = heapq.heappop(pq)`: Get the cell with the smallest cur_time from the queue.\n - `if i == m - 1 and j == n - 1: return cur_time`: If the current cell is the destination, return the `cur_time`.\n - `new_move_time = 2 if move_time == 1 else 1`: Calculate the move time for the next step based on the current `move_time`.\n - `for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:`: Explore the four neighboring cells (up, down, left, right).\n - `ni, nj = i + di, j + dj`: Calculate the coordinates of the neighbor.\n - `if ni < 0 or ni == m or nj < 0 or nj == n: continue`: Skip if the neighbor is out of bounds.\n - `new_time = max(cur_time, moveTime[ni][nj]) + new_move_time:` Calculate the time to reach the neighbor. It\'s the maximum of the current time and the move time of the neighbor cell, plus the `new_move_time`.\n - `if min_time[ni][nj] > new_time`: If this new time is shorter than the current minimum time to reach the neighbor, update `min_time` and add the neighbor to the priority queue.\n\n- `Return -1`: If the loop finishes without finding a path to the destination (which shouldn\'t happen in this scenario), the code returns -1.\n\n**In Summary**\n\nThis code efficiently finds the minimum time to navigate a grid with varying move times between cells. It uses a priority queue to prioritize exploration and a modified Dijkstra\'s algorithm to find the shortest path based on the time constraints.\n\n# Complexity\n- Time complexity: $$O(N * M log(N * M))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N * M)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m, n = len(moveTime), len(moveTime[0])\n min_time = [[float("inf") for _ in range(n)] for _ in range(m)]\n min_time[0][0] = 0\n pq = [(0, 0, 0, 2)]\n while pq:\n cur_time, i, j, move_time = heapq.heappop(pq)\n if i == m - 1 and j == n - 1: return cur_time\n new_move_time = 2 if move_time == 1 else 1\n for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n ni, nj = i + di, j + dj\n if ni < 0 or ni == m or nj < 0 or nj == n: continue\n new_time = max(cur_time, moveTime[ni][nj]) + new_move_time\n if min_time[ni][nj] > new_time:\n min_time[ni][nj] = new_time\n heapq.heappush(pq, (new_time, ni, nj, new_move_time))\n return -1\n```\n```C++ []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m = moveTime.size();\n int n = moveTime[0].size();\n vector<vector<int>> min_time(m, vector<int>(n, numeric_limits<int>::max()));\n min_time[0][0] = 0;\n priority_queue<tuple<int, int, int, int>, vector<tuple<int, int, int, int>>, greater<tuple<int, int, int, int>>> pq;\n pq.push({0, 0, 0, 2}); \n\n while (!pq.empty()) {\n auto [cur_time, i, j, move_time] = pq.top();\n pq.pop();\n if (i == m - 1 && j == n - 1) return cur_time;\n int new_move_time = (move_time == 1) ? 2 : 1;\n for (auto [di, dj] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {\n int ni = i + di, nj = j + dj;\n if (ni < 0 || ni == m || nj < 0 || nj == n) continue;\n int new_time = max(cur_time, moveTime[ni][nj]) + new_move_time;\n if (min_time[ni][nj] > new_time) {\n min_time[ni][nj] = new_time;\n pq.push({new_time, ni, nj, new_move_time});\n }\n }\n }\n return -1;\n }\n};\n```\n``` java[]\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n int m = moveTime.length;\n int n = moveTime[0].length;\n int[][] min_time = new int[m][n];\n for (int i = 0; i < m; i++) {\n Arrays.fill(min_time[i], Integer.MAX_VALUE);\n }\n min_time[0][0] = 0;\n PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); \n pq.offer(new int[]{0, 0, 0, 2}); \n\n while (!pq.isEmpty()) {\n int[] entry = pq.poll();\n int cur_time = entry[0], i = entry[1], j = entry[2], move_time = entry[3];\n if (i == m - 1 && j == n - 1) return cur_time;\n int new_move_time = (move_time == 1) ? 2 : 1;\n int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n for (int[] dir : dirs) {\n int ni = i + dir[0], nj = j + dir[1];\n if (ni < 0 || ni == m || nj < 0 || nj == n) continue;\n int new_time = Math.max(cur_time, moveTime[ni][nj]) + new_move_time;\n if (min_time[ni][nj] > new_time) {\n min_time[ni][nj] = new_time;\n pq.offer(new int[]{new_time, ni, nj, new_move_time});\n }\n }\n }\n return -1;\n }\n}\n```\n | 4 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++', 'Java', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | [C++] Djikstra's + Easy Hack for deciding between 1 or 2 (Even vs Odd Diagonal) | c-djikstras-easy-hack-for-deciding-betwe-u2ga | Intuition\n Describe your first thoughts on how to solve this problem. \nSame approach as 3341. but instead we have to account for either adding 1 or 2 dependin | frvnk | NORMAL | 2024-11-03T04:22:20.727121+00:00 | 2024-11-03T18:00:32.888421+00:00 | 559 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSame approach as [3341.](https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/description/) but instead we have to account for either adding 1 or 2 depending on the room. Note that traveling into rooms on odd diagonals will always require a time of $2$ seconds while rooms on the even diagonals always require $1$ second. This can be quickly identified by the boolean value `evenCol = (newCol+newRow)%2`, where `newCol` and `newRow` are the col and row index of the room we\'re trying to move into.\n\n# Approach\nModified Djikstra\'s\n# Complexity\n- Time complexity:\n$O((V + E) \\log V) = O((mn+4mn)\\log(mn))=O(mn\\cdot\\log (mn))$\n- Space complexity:\n$O(V) = O(mn)$\n# Code\n```cpp []\nclass Solution {\nconst vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n //Djikstra\n int n = moveTime.size();\n int m = moveTime[0].size();\n //distance from 0,0 to i,j\n vector<vector<int>> dist(n, vector<int>(m, INT_MAX));\n dist[0][0] = 0;\n \n //Priority Queue to maintain closest room we have not visited yet\n priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq;\n pq.push({0, 0, 0});\n while (!pq.empty()) {\n auto [currentDist, row, col] = pq.top();\n pq.pop();\n \n if (row == n - 1 && col == m - 1) {\n return currentDist; \n }\n \n for (const auto& [dx, dy] : directions) {\n int newRow = row + dx;\n int newCol = col + dy;\n \n if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m) {\n int travelTime = 2-(newRow+newCol)%2; // =(newRow+newCol)%2? 1:2;\n \n int newDist = max(currentDist, moveTime[newRow][newCol])+travelTime;\n \n if (newDist < dist[newRow][newCol]) {\n dist[newRow][newCol] = newDist;\n pq.push({newDist, newRow, newCol});\n }\n }\n }\n } \n return dist[n-1][m-1];\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
find-minimum-time-to-reach-last-room-ii | Constest - 3/11/2024 || Q-3 || BFS || Heap | constest-3112024-q-3-bfs-heap-by-sajalti-qekl | Approach\n\n1. Modeling the Problem:\n - Each cell in the grid represents a point that can be traversed, with a cost associated with moving into that cell def | sajaltiwari007 | NORMAL | 2024-11-03T04:10:09.116772+00:00 | 2024-11-03T04:10:09.116794+00:00 | 97 | false | ### Approach\n\n1. **Modeling the Problem**:\n - Each cell in the grid represents a point that can be traversed, with a cost associated with moving into that cell defined by the `moveTime` array.\n - The objective is to minimize the time taken to reach the cell at `(n-1, m-1)` starting from `(0, 0)`.\n\n2. **Data Structure**:\n - A priority queue (min-heap) is used to explore the cell with the minimum time first. This is crucial for Dijkstra-like algorithms to ensure that once a cell\'s minimum time is finalized, it is not updated again.\n\n3. **Pair Class**:\n - The `Pair` class holds the information about the current cell\'s coordinates (`row`, `col`), the accumulated time (`time`), and an additional field (`which`) to determine the increment added to the time in the next steps.\n\n4. **Initialization**:\n - The `minTime` 2D array is initialized to store the minimum time to reach each cell, starting with `Long.MAX_VALUE` to indicate that all cells are initially unreachable except the starting cell which is set to `0`.\n\n5. **Traversal Logic**:\n - The algorithm processes cells by expanding to their neighbors (up, down, left, right).\n - For each neighbor, it calculates the new time based on the current time and the value in the `moveTime` grid.\n - If the new calculated time is less than the stored time for that neighbor, it updates the `minTime` for that cell and adds it to the priority queue for further exploration.\n\n6. **Termination**:\n - If the algorithm reaches the target cell `(n-1, m-1)`, it returns the time taken to reach there. If the queue is exhausted without reaching the target, it returns `-1`, indicating that the target is unreachable.\n\n### Intuition\n\nThe core intuition behind the algorithm is to always expand the least costly option available (in terms of time) to ensure the shortest path to the target. By using a priority queue, the algorithm efficiently picks the next cell to explore based on the least accumulated time, mimicking the behavior of breadth-first search with a cost metric.\n\n### Time Complexity\n\n- **Time Complexity**: The complexity is \\(O((n*m) \\log(n * m))\\), where \\(n\\) is the number of rows and \\(m\\) is the number of columns. This arises because:\n - Each cell (total of \\(n * m\\)) may be added to the priority queue at most once.\n - The `offer` operation on the priority queue takes \\(O(log k)\\) time, where \\(k\\) is the number of elements in the queue.\n\n### Space Complexity\n\n- **Space Complexity**: The space complexity is \\(O(n * m)\\) for storing the `minTime` array and the priority queue that may potentially hold all cells in the worst case.\n\n### Summary\n\nThis approach efficiently finds the minimum time to traverse a grid while considering the movement cost defined by the `moveTime` array. The use of a priority queue ensures optimal selection of paths, which is key in pathfinding algorithms like Dijkstra\'s. The code structure is clean and modular, making it easy to understand and maintain.\n\n# Code\n```java []\nimport java.util.*;\n\nclass Solution {\n class Pair implements Comparable<Pair> {\n int row;\n int col;\n long time;\n int which;\n\n Pair(int r, int c, long t,int w) {\n this.row = r;\n this.col = c;\n this.time = t;\n this.which = w;\n }\n\n @Override\n public int compareTo(Pair other) {\n return Long.compare(this.time, other.time);\n }\n }\n\n public int minTimeToReach(int[][] moveTime) {\n int n = moveTime.length;\n int m = moveTime[0].length;\n\n // Priority queue for minimum time expansion (Dijkstra-like)\n PriorityQueue<Pair> pq = new PriorityQueue<>();\n pq.offer(new Pair(0, 0, 0L,-1));\n\n // Minimum time to reach each cell, initialized to a large number\n long[][] minTime = new long[n][m];\n for (int i = 0; i < n; i++) {\n Arrays.fill(minTime[i], Long.MAX_VALUE);\n }\n minTime[0][0] = 0L;\n\n // Direction vectors for moving up, down, left, right\n int[] dx = {0, 0, 1, -1};\n int[] dy = {1, -1, 0, 0};\n\n while (!pq.isEmpty()) {\n Pair current = pq.poll();\n int r = current.row, c = current.col;\n long t = current.time;\n int add = (current.which==1?2:1);\n\n // If we reached the target cell, return the minimum time (converted to int)\n if (r == n - 1 && c == m - 1) return (int) t;\n\n // Explore neighbors\n for (int i = 0; i < 4; i++) {\n int rr = r + dx[i];\n int cc = c + dy[i];\n\n if (rr >= 0 && rr < n && cc >= 0 && cc < m) {\n long newTime = Math.max(t + add, (long)(moveTime[rr][cc]+add));\n\n // Only add to queue if it\'s an improvement\n if (minTime[rr][cc] > newTime) {\n minTime[rr][cc] = newTime;\n pq.offer(new Pair(rr, cc, newTime,add));\n }\n }\n }\n }\n\n return -1; // If unreachable (edge case)\n }\n}\n\n\n``` | 3 | 0 | ['Breadth-First Search', 'Heap (Priority Queue)', 'Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Simple C++ Solution || (Using Dijkstra's Algo) ✅✅ | simple-c-solution-using-dijkstras-algo-b-3ycn | Code\ncpp []\nclass Solution {\npublic:\n int di[4]={1,-1,0,0};\n int dj[4]={0,0,1,-1};\n int minTimeToReach(vector<vector<int>>& moveTime) {\n | Abhi242 | NORMAL | 2024-11-04T14:48:51.653287+00:00 | 2024-11-04T14:48:51.653325+00:00 | 115 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int di[4]={1,-1,0,0};\n int dj[4]={0,0,1,-1};\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n=moveTime.size();\n int m=moveTime[0].size();\n vector<vector<int>> dist(n,vector<int>(m,INT_MAX));\n priority_queue<pair<int,pair<int,pair<int,int>>>,vector<pair<int,pair<int,pair<int,int>>>>,greater<pair<int,pair<int,pair<int,int>>>>> pq;\n pq.push({0,{1,{0,0}}});\n while(!pq.empty()){\n auto topu=pq.top();\n int t=topu.first;\n int c=topu.second.first;\n int i=topu.second.second.first;\n int j=topu.second.second.second;\n pq.pop();\n for(int k=0;k<4;k++){\n int ni=i+di[k];\n int nj=j+dj[k];\n if(ni>=0 && nj>=0 && ni<n && nj<m && dist[ni][nj]>(c+max(t,moveTime[ni][nj]))){ \n dist[ni][nj]=(c+max(t,moveTime[ni][nj]));\n pq.push({dist[ni][nj],{c==1?2:1,{ni,nj}}});\n\n }\n }\n }\n return dist[n-1][m-1];\n }\n};\n``` | 2 | 0 | ['Graph', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | EASY C++ Solution Beats 100% of the user || find-minimum-time-to-reach-last-room-ii | easy-c-solution-beats-100-of-the-user-fi-f2ra | \n\n# Code\ncpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& mv) {\n int m = mv.size();\n int n = mv[0].size(); \n | ZugsWang | NORMAL | 2024-11-03T08:37:49.213320+00:00 | 2024-11-03T08:37:49.213353+00:00 | 132 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& mv) {\n int m = mv.size();\n int n = mv[0].size(); \n priority_queue<pair<pair<int,int>,pair<int,int>>,vector<pair<pair<int,int>,pair<int,int>>>,greater<pair<pair<int,int>,pair<int,int>>>>pq;//{{t,len},{x,y}};\n vector<vector<int>>res(m,vector<int>(n,INT_MAX));\n res[0][0]=0;\n pq.push({{0,2},{0,0}});//2 signify that next coloum will get 1 in addition in time\n int delr[]={-1,0,+1,0};\n int delc[]={0,-1,0,+1};\n while(!pq.empty()){\n int t = pq.top().first.first;\n int len = pq.top().first.second;\n int x = pq.top().second.first;\n int y = pq.top().second.second;\n if(x==m-1&&y==n-1){\n return t;\n }\n pq.pop();\n for(int i=0;i<4;i++){\n int nrow = x + delr[i];\n int ncol = y + delc[i];\n if(nrow>=0&&nrow<m&&ncol>=0&&ncol<n){\n int newdist ;\n if(len == 2){\n newdist = max(t+1,mv[nrow][ncol]+1);\n if(newdist< res[nrow][ncol]){\n res[nrow][ncol]=newdist;\n pq.push({{newdist,1},{nrow,ncol}});\n } \n }else{\n newdist = max(t+2,mv[nrow][ncol]+2);\n if(newdist<res[nrow][ncol]){\n res[nrow][ncol]=newdist;\n pq.push({{newdist,2},{nrow,ncol}});\n }\n }\n }\n }\n\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['Breadth-First Search', 'Graph', 'Heap (Priority Queue)', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Python Solution | python-solution-by-pranav743-2c20 | Approach\nShortest Path Algoritm - Dijkstra\'s\n\n# Complexity\n- Time complexity: O( (nm) * log(nm) )\n- Space complexity: O(2nm)\n\n# Code\npython3 []\nclass | pranav743 | NORMAL | 2024-11-03T04:03:21.620528+00:00 | 2024-11-03T04:03:21.620552+00:00 | 156 | false | # Approach\nShortest Path Algoritm - Dijkstra\'s\n\n# Complexity\n- Time complexity: $$O( (n*m) * log(n*m) )$$\n- Space complexity: $$O(2*n*m)$$\n\n# Code\n```python3 []\nclass Solution:\n def minTimeToReach(self, matrix: List[List[int]]) -> int:\n\n num_rows = len(matrix)\n num_cols = len(matrix[0])\n visited = [[False for _ in range(num_cols)] for _ in range(num_rows)]\n\n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n\n priority_queue = [(0, 0, 0, True)] # time, row, col, is_day\n\n while priority_queue:\n time, row, col, is_day = heapq.heappop(priority_queue)\n \n if row == num_rows - 1 and col == num_cols - 1:\n return time\n \n for dx, dy in directions:\n new_row, new_col = row + dx, col + dy\n if (new_row >= num_rows or new_col >= num_cols or \n new_row < 0 or new_col < 0 or visited[new_row][new_col]):\n continue\n visited[new_row][new_col] = True\n additional_time = 1 if is_day else 2\n heapq.heappush(priority_queue, (max(time + additional_time, matrix[new_row][new_col] + additional_time), new_row, new_col, not is_day))\n return -1\n``` | 2 | 0 | ['Heap (Priority Queue)', 'Shortest Path', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Java Clean Solution - 3/11/2024 | java-clean-solution-3112024-by-shree_gov-sbid | Complexity\n- Time complexity:O(nm)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(nm*2)\n Add your space complexity here, e.g. O(n) \n\n# | Shree_Govind_Jee | NORMAL | 2024-11-03T04:03:13.664119+00:00 | 2024-11-03T04:03:13.664145+00:00 | 141 | false | # Complexity\n- Time complexity:$$O(n*m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n*m*2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Pair implements Comparable<Pair> {\n int x;\n int y;\n int parity;\n int time;\n\n public Pair(int x, int y, int time, int parity) {\n this.x = x;\n this.y = y;\n this.parity = parity;\n this.time = time;\n }\n\n @Override\n public int compareTo(Pair p) {\n return Integer.compare(this.time, p.time);\n }\n}\n\nclass Solution {\n int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n public int minTimeToReach(int[][] moveTime) {\n int n = moveTime.length, m = moveTime[0].length;\n\n int[][][] dist = new int[n][m][2];\n for (int[][] d : dist) {\n for (int i = 0; i < m; i++) {\n d[i][0] = Integer.MAX_VALUE;\n d[i][1] = Integer.MAX_VALUE;\n }\n }\n\n PriorityQueue<Pair> pq = new PriorityQueue<>();\n pq.add(new Pair(0, 0, 0, 0));\n dist[0][0][0] = 0;\n\n while (!pq.isEmpty()) {\n Pair top = pq.poll();\n int x = top.x, y = top.y;\n int time = top.time;\n int par = top.parity;\n\n if (time > dist[x][y][par]) {\n continue;\n }\n\n for (int[] d : dirs) {\n int nx = x + d[0], ny = y + d[1];\n\n if (nx >= 0 && nx < n && ny >= 0 && ny < m) {\n int nt;\n if (par == 0) {\n nt = 1 + Math.max(time, moveTime[nx][ny]);\n } else {\n nt = 2 + Math.max(time, moveTime[nx][ny]);\n }\n\n if (nt < dist[nx][ny][1 - par]) {\n dist[nx][ny][1 - par] = nt;\n pq.offer(new Pair(nx, ny, nt, 1 - par));\n }\n }\n }\n }\n return Math.min(dist[n - 1][m - 1][0], dist[n - 1][m - 1][1]);\n }\n}\n``` | 2 | 1 | ['Array', 'Math', 'Dynamic Programming', 'Queue', 'Heap (Priority Queue)', 'Java'] | 1 |
find-minimum-time-to-reach-last-room-ii | ✅ Simple Java Solution + Heap | simple-java-solution-heap-by-harsh__005-47e7 | CODE\nJava []\nint[][] dirs = new int[][]{{-1,0}, {1,0}, {0,-1}, {0,1}};\npublic int minTimeToReach(int[][] moveTime) {\n int n=moveTime.length, m = moveTime | Harsh__005 | NORMAL | 2024-11-03T04:02:14.296718+00:00 | 2024-11-03T04:10:02.199710+00:00 | 261 | false | ## **CODE**\n```Java []\nint[][] dirs = new int[][]{{-1,0}, {1,0}, {0,-1}, {0,1}};\npublic int minTimeToReach(int[][] moveTime) {\n int n=moveTime.length, m = moveTime[0].length;\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[2]-b[2]);\n\t\n\t// 0 -> R, 1 -> C, 2 -> Cost to Reach that Room, 3 -> First or Second Move\n pq.add(new int[]{0,0,0,1});\n \n int dp[][] = new int[n][m];\n for(int[] arr: dp) Arrays.fill(arr, -1);\n dp[0][0] = 0;\n \n while(!pq.isEmpty()) {\n int[] top = pq.remove();\n int r=top[0], c=top[1], add = top[3];\n \n for(int[] dir : dirs) {\n int nr=r+dir[0], nc=c+dir[1];\n if(nr<0 || nc<0 || nr==n || nc==m) continue;\n \n int cost = Math.max(moveTime[nr][nc], top[2]) + add;\n if(nr == n-1 && nc == m-1) return cost;\n \n if(dp[nr][nc] == -1 || dp[nr][nc] > cost) {\n dp[nr][nc] = cost;\n pq.add(new int[]{nr,nc,cost,(top[3]==1)? 2: 1});\n }\n }\n }\n return -1;\n}\n``` | 2 | 0 | ['Java'] | 1 |
find-minimum-time-to-reach-last-room-ii | c++ solution | c-solution-by-dilipsuthar60-l5nj | \nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& mat) {\n int n=mat.size();\n int m=mat[0].size();\n priority_queue | dilipsuthar17 | NORMAL | 2024-11-03T04:01:40.282722+00:00 | 2024-11-03T04:01:40.282749+00:00 | 186 | false | ```\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& mat) {\n int n=mat.size();\n int m=mat[0].size();\n priority_queue<tuple<long long,long long,int>,vector<tuple<long long,long long,int>>,greater<tuple<long long,long long,int>>>pq;\n vector<pair<int,int>>d={{-1,0},{1,0},{0,1},{0,-1}};\n vector<vector<long long>>dis(n,vector<long long>(m,1e18));\n pq.push({0,0,0});\n dis[0][0]=0;\n vector<vector<int>>vis(n,vector<int>(m,0));\n long long time=0;\n while(pq.size()){\n auto [cost,xy,type]=pq.top();\n pq.pop();\n int x=xy/m;\n int y=xy%m;\n if(vis[x][y]) continue;\n vis[x][y]=1;\n for(auto &it:d){\n int nx=x+it.first;\n int ny=y+it.second;\n if(nx>=0&&ny>=0&&nx<n&&ny<m){\n long long alter =(type==0)?1:2;\n time=cost+alter;\n long long actualTime=max(time,1ll*mat[nx][ny]+alter);\n if(actualTime<dis[nx][ny]){\n dis[nx][ny]=actualTime;\n pq.push({dis[nx][ny],nx*m+ny,type^1});\n }\n }\n }\n }\n return dis[n-1][m-1];\n }\n};\n``` | 2 | 1 | ['C', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkstra - Intuition based | modified-dijkstra-intuition-based-by-shi-dutx | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | shivanshudobhal | NORMAL | 2025-03-20T06:13:01.704708+00:00 | 2025-03-20T06:13:01.704708+00:00 | 46 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public: //time, 1or2 //row, col
typedef pair<int,pair<int,pair<int,int>>> pii;
int minTimeToReach(vector<vector<int>>& moveTime) {
int n = moveTime.size();
int m = moveTime[0].size();
vector<vector<int>> dist(n,vector<int>(m,INT_MAX));
int delRow[] = {-1,0,1,0};
int delCol[] = {0,1,0,-1};
priority_queue<pii,vector<pii>,greater<pii>> minh;
minh.push({0,{1,{0,0}}});
dist[0][0];
while(!minh.empty()){
int curr_time = minh.top().first;
int _1or2 = minh.top().second.first;
int row = minh.top().second.second.first;
int col = minh.top().second.second.second;
minh.pop();
for(int i=0;i<4;i++){
int nrow = row + delRow[i];
int ncol = col + delCol[i];
if(nrow>=0 && nrow<n && ncol>=0 && ncol<m){
int time = moveTime[nrow][ncol];
if(curr_time<time) {
dist[nrow][ncol] = time + _1or2;
int temp = _1or2==1?2:1;
minh.push({time+_1or2,{temp,{nrow,ncol}}});
} else {
if(dist[nrow][ncol]> curr_time + _1or2 ){
dist[nrow][ncol] = curr_time + _1or2;
int temp = _1or2==1?2:1;
minh.push({curr_time+_1or2,{temp,{nrow,ncol}}});
}
}
}
}
}
return dist[n-1][m-1];
}
};
``` | 1 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | [Java] Easy solution with min Heap | java-easy-solution-with-min-heap-by-ytch-ilzk | java\nclass Solution {\n public int minTimeToReach(final int[][] moveTime) {\n final int n = moveTime.length, m = moveTime[0].length;\n final Q | YTchouar | NORMAL | 2024-11-07T23:08:19.281096+00:00 | 2024-11-07T23:08:19.281133+00:00 | 38 | false | ```java\nclass Solution {\n public int minTimeToReach(final int[][] moveTime) {\n final int n = moveTime.length, m = moveTime[0].length;\n final Queue<int[]> queue = new PriorityQueue<>((a, b) -> a[2] - b[2]);\n final int[][] dp = new int[n][m];\n final int[][] directions = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };\n\n for(final int[] d : dp)\n Arrays.fill(d, Integer.MAX_VALUE);\n\n queue.offer(new int[] { 0, 0, 0, 1 });\n moveTime[0][0] = 0;\n\n while(!queue.isEmpty()) {\n final int[] curr = queue.poll();\n final int i = curr[0], j = curr[1], t = curr[2], cost = curr[3];\n\n if(i == n - 1 && j == m - 1)\n return t;\n\n if(dp[i][j] <= t)\n continue;\n\n dp[i][j] = t;\n\n for(final int[] direction : directions) {\n final int x = i + direction[0], y = j + direction[1];\n\n if(x < n && y < m && x >= 0 && y >= 0 && dp[x][y] == Integer.MAX_VALUE) {\n final int newTime = Math.max(t, moveTime[x][y]) + cost;\n queue.offer(new int[] { x, y, newTime, cost == 1 ? 2 : 1 });\n }\n }\n }\n\n return -1;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Why don't AC solutions consider cost state in distance calculation ? | why-dont-ac-solutions-consider-cost-stat-yi54 | \n Describe your first thoughts on how to solve this problem. \nAll of them use djisktra to normalise weight with the condition\nAssuming dist[i][j] -> Minimum | y_g | NORMAL | 2024-11-07T15:21:28.488797+00:00 | 2024-11-07T15:21:28.488835+00:00 | 7 | false | \n<!-- Describe your first thoughts on how to solve this problem. -->\nAll of them use djisktra to normalise weight with the condition\nAssuming dist[i][j] -> Minimum time to reach (i,j)\nAnd we insert into PQ (Min Heap) as (minArrivalTime, nextStepCost, nextRow, nextCol)\nAlso assume matrix[n-1][m-1] = 0 (To simply say it has no restriction)\nConsider a m*n matrix\n\nSuppose I reach a state where I calculate dist[n-1][m-2] = 10, and I reached to this state with a cost of moving as 1, hence to move to (n-1,m-1) the cost would be 2, so when this tuple will be popped and evaluated dist[n-1][m-1] will be set as 12(10+2).And we will push the state (10,2,n-1,m-2) to pq.\n\nHowever there might be case where through some alternate route later in the algorithm we reach (n-1,m-2) with a distance of 10 again but this time I reach with a cost of 2, so to move to n-1,m-1 the cost will be 1, and total distance will be 10 + 1. But if we check normalisation process it will check if\n\ndist[n-1][m-2] > currArrivalTime (but since they are equal this would fail)\nand we would never push the state (10,1,n-1,m-2) on the pq.\n\nAnd since the state wouldn\'t be evaluated the answer might be wrong.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& vec) {\n int n = vec.size();\n int m = vec[0].size();\n\n priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;\n vector<vector<int>> dist(n, vector<int>(m, INT_MAX));\n vector<int> dirx = {1, 0, -1, 0};\n vector<int> diry = {0, 1, 0, -1};\n\n pq.push({0, 1, 0, 0});\n\n dist[0][0] = 0;\n int x,y,time,cost,nx, ny;\n\n while (!pq.empty()) {\n auto p = pq.top();\n pq.pop();\n x = p[2];\n y = p[3];\n time = p[0];\n cost = p[1];\n\n for (int i = 0; i < 4; i++) {\n nx = x + dirx[i];\n ny = y + diry[i];\n\n if (isValid(nx, ny, n, m)) {\n int ntime;\n if (vec[nx][ny] >= time) {\n ntime = vec[nx][ny] + cost;\n } else {\n ntime = time + cost;\n }\n\n if (dist[nx][ny] > ntime) {\n dist[nx][ny] = ntime;\n pq.push({ntime, cost == 1 ? 2 : 1, nx, ny});\n }\n }\n }\n }\n return dist[n-1][m-1];\n }\n\n bool isValid(int x, int y, int r, int c) {\n if (x < 0 || y < 0 || x >= r || y >= c)\n return false;\n return true;\n }\n };\n``` | 1 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | [C++] Dijkstra once again | c-dijkstra-once-again-by-bora_marian-n4he | Same approach Like solution: https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/solutions/6011112/c-dijkstra-algorithm-implemented-using-a-set | bora_marian | NORMAL | 2024-11-05T19:48:00.674234+00:00 | 2024-11-05T19:48:00.674267+00:00 | 117 | false | Same approach Like solution: https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/solutions/6011112/c-dijkstra-algorithm-implemented-using-a-set/\nA Dijkstra implementation processing the cells with the smallest time first.\nThe difference between the 2 solutions is that we keep track also of the distance in cells in order to add + 1 or +2 alternatively.\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n vector<int> di = {0, 0, 1, -1}, dj = {1, -1, 0, 0};\n int n = moveTime.size(), m = moveTime[0].size();\n vector<vector<int>> t(n + 1, vector<int>(m + 1, -1)); //min time to reach[i][j]\n set<vector<int>> ord_pos; // [time, i, j, distance]\n t[0][0] = 0;\n ord_pos.insert({0, 0, 0, 0}); //[0] -time, i, j, distance in cells.\n while(!ord_pos.empty()) {\n vector<int> front = *ord_pos.begin();\n ord_pos.erase(ord_pos.begin());\n\n if (t[front[1]][front[2]] != -1 && front[0] > t[front[1]][front[2]]) //no improvement\n continue;\n int d = (front[3] + 1) % 2 == 1 ? 1 : 2;\n for (int k = 0; k < 4; k++) {\n int newposi = front[1] + di[k];\n int newposj = front[2] + dj[k];\n if (!is_valid(newposi, newposj, n, m))\n continue;\n \n if (t[newposi][newposj] == -1) {\n if (front[0] <= moveTime[newposi][newposj]) {\n t[newposi][newposj] = moveTime[newposi][newposj] + d;\n } else {\n t[newposi][newposj] = front[0] + d;\n }\n ord_pos.insert({t[newposi][newposj], newposi, newposj, front[3] + 1});\n continue;\n }\n if (front[0] + d < t[newposi][newposj] && front[0] >= moveTime[newposi][newposj]) {\n t[newposi][newposj] = front[0] + d;\n ord_pos.insert({t[newposi][newposj], newposi, newposj, front[3] + 1});\n }\n \n }\n }\n return t[n-1][m-1];\n }\n bool is_valid(int i, int j, int n, int m) {\n return i >= 0 && j >= 0 && i < n && j < m;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | BFS | bfs-by-pragati3003-ukwa | \n\n# Code\ncpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size();\n int m = moveTi | Pragati3003 | NORMAL | 2024-11-03T14:48:41.779992+00:00 | 2024-11-03T14:48:41.780019+00:00 | 18 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size();\n int m = moveTime[0].size();\n priority_queue<tuple<int, int, int, bool>,\n vector<tuple<int, int, int, bool>>, greater<>>\n pq;\n\n vector<vector<int>> minTime(n, vector<int>(m, INT_MAX));\n minTime[0][0] = 0;\n pq.push({0, 0, 0, false});\n\n vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n while (!pq.empty()) {\n auto [currTime, x, y, turn] = pq.top();\n pq.pop();\n\n if (x == n - 1 && y == m - 1) {\n return currTime;\n }\n\n int waitTime = (turn == false) ? 1 : 2;\n\n for (auto [dx, dy] : directions) {\n int nx = x + dx;\n int ny = y + dy;\n\n if (nx >= 0 && nx < n && ny >= 0 && ny < m) {\n int newWaitTime =\n max(currTime + waitTime, moveTime[nx][ny] + waitTime);\n\n if (newWaitTime < minTime[nx][ny]) {\n minTime[nx][ny] = newWaitTime;\n pq.push({newWaitTime, nx, ny, !turn});\n }\n }\n }\n }\n\n return -1;\n }\n};\n``` | 1 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Easy Dijkstra's solution using min heap | easy-dijkstras-solution-using-min-heap-b-u0f9 | Intution\nUsing Dijkstras \n1. For finding the shortest path from starting point to ending point , the first approach comes in mind is dijkstras shortest path | be_fighter | NORMAL | 2024-11-03T08:03:37.914808+00:00 | 2024-11-03T08:03:37.914852+00:00 | 100 | false | # Intution\nUsing Dijkstras \n1. For finding the shortest path from starting point to ending point , the first approach comes in mind is dijkstras shortest path algorithm\n2. There is slight modification in algorithm according the question \n3. In even move it take +2 seconds and on odd +1 seconds\n4. We have take min heap to stor {time, row, column,turn};\nOther all is similar to normal dijkstras\'s algoirthm\n\n# Complexity\n- Time complexity:\nO(m * n * log(m * n))\n\n- Space complexity:\nO(m * n)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n=moveTime.size();\n int m=moveTime[0].size();\n\n priority_queue<pair<long long,pair<long long,pair<long long,long long>>>,vector<pair<long long,pair<long long,pair<long long,long long>>>>,greater<pair<long long,pair<long long,pair<long long,long long>>>>>pq;\n \n vector<vector<long long>>dist(n,vector<long long>(m,INT_MAX));\n\n pq.push({0,{0,{0,1}}});\n dist[0][0]=0;\n\n while(!pq.empty()){\n long long time=pq.top().first;\n int row=pq.top().second.first;\n int col=pq.top().second.second.first;\n int turn=pq.top().second.second.second;\n pq.pop();\n\n if(row==n-1 && col==m-1){\n return time;\n }\n\n int drow[4]={-1,0,1,0};\n int dcol[4]={0,1,0,-1};\n\n for(int i=0;i<4;i++){\n int nrow=row+drow[i];\n int ncol=col+dcol[i];\n \n if(nrow>=0 && ncol>=0 && nrow<n && ncol<m){\n long long maxtime;\n if(turn==1){\n maxtime=max(time,1ll*moveTime[nrow][ncol])+1;\n }\n else{\n maxtime=max(time,1ll*moveTime[nrow][ncol])+2;\n }\n \n if( dist[nrow][ncol]>maxtime){\n dist[nrow][ncol]=maxtime;\n pq.push({maxtime,{nrow,{ncol,!turn}}});\n\n }\n }\n }\n }\n return -1;\n }\n};\n```\n```java []\nimport java.util.PriorityQueue;\n\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n int n = moveTime.length;\n int m = moveTime[0].length;\n\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));\n long[][] dist = new long[n][m];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n dist[i][j] = Long.MAX_VALUE;\n }\n }\n\n pq.offer(new int[]{0, 0, 0, 1}); // {time, row, col, turn}\n dist[0][0] = 0;\n\n int[] drow = {-1, 0, 1, 0};\n int[] dcol = {0, 1, 0, -1};\n\n while (!pq.isEmpty()) {\n int[] curr = pq.poll();\n long time = curr[0];\n int row = curr[1];\n int col = curr[2];\n int turn = curr[3];\n\n if (row == n - 1 && col == m - 1) {\n return (int) time;\n }\n\n for (int i = 0; i < 4; i++) {\n int nrow = row + drow[i];\n int ncol = col + dcol[i];\n\n if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m) {\n long maxTime = (turn == 1) ? Math.max(time, moveTime[nrow][ncol]) + 1 : Math.max(time, moveTime[nrow][ncol]) + 2;\n\n if (dist[nrow][ncol] > maxTime) {\n dist[nrow][ncol] = maxTime;\n pq.offer(new int[]{(int) maxTime, nrow, ncol, 1 - turn});\n }\n }\n }\n }\n return -1;\n }\n}\n\n```\n```python []\nimport heapq\nimport sys\n\nclass Solution:\n def minTimeToReach(self, moveTime):\n n, m = len(moveTime), len(moveTime[0])\n pq = []\n heapq.heappush(pq, (0, 0, 0, 1)) # (time, row, col, turn)\n dist = [[sys.maxsize] * m for _ in range(n)]\n dist[0][0] = 0\n\n drow = [-1, 0, 1, 0]\n dcol = [0, 1, 0, -1]\n\n while pq:\n time, row, col, turn = heapq.heappop(pq)\n\n if row == n - 1 and col == m - 1:\n return time\n\n for i in range(4):\n nrow, ncol = row + drow[i], col + dcol[i]\n\n if 0 <= nrow < n and 0 <= ncol < m:\n maxtime = max(time, moveTime[nrow][ncol]) + (1 if turn == 1 else 2)\n\n if dist[nrow][ncol] > maxtime:\n dist[nrow][ncol] = maxtime\n heapq.heappush(pq, (maxtime, nrow, ncol, 1 - turn))\n\n return -1\n\n```\n```javascript []\nclass Solution {\n minTimeToReach(moveTime) {\n const n = moveTime.length;\n const m = moveTime[0].length;\n \n const pq = new MinPriorityQueue({ priority: x => x[0] });\n const dist = Array.from({ length: n }, () => Array(m).fill(Number.MAX_SAFE_INTEGER));\n \n pq.enqueue([0, 0, 0, 1]); // [time, row, col, turn]\n dist[0][0] = 0;\n\n const drow = [-1, 0, 1, 0];\n const dcol = [0, 1, 0, -1];\n\n while (!pq.isEmpty()) {\n const [time, row, col, turn] = pq.dequeue().element;\n\n if (row === n - 1 && col === m - 1) {\n return time;\n }\n\n for (let i = 0; i < 4; i++) {\n const nrow = row + drow[i];\n const ncol = col + dcol[i];\n\n if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m) {\n const maxtime = Math.max(time, moveTime[nrow][ncol]) + (turn === 1 ? 1 : 2);\n\n if (dist[nrow][ncol] > maxtime) {\n dist[nrow][ncol] = maxtime;\n pq.enqueue([maxtime, nrow, ncol, 1 - turn]);\n }\n }\n }\n }\n return -1;\n }\n}\n\n```\n\n | 1 | 0 | ['Depth-First Search', 'Heap (Priority Queue)', 'Shortest Path', 'C++', 'Java', 'Python3', 'JavaScript'] | 1 |
find-minimum-time-to-reach-last-room-ii | Dijkstra with one extra state | c++ | dijkstra-with-one-extra-state-c-by-karna-buan | I hope you are clear with 1st part of the problem where this move_made part was not there and rest was the same problem\nlink to my editorial for that problem - | karna001 | NORMAL | 2024-11-03T04:41:43.323528+00:00 | 2024-11-03T04:41:43.323553+00:00 | 94 | false | I hope you are clear with 1st part of the problem where this move_made part was not there and rest was the same problem\nlink to my editorial for that problem - https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/discuss/6000326/Dijkstra-or-Graph-or-c%2B%2B\n\nso here the extra catch is :\n**Moving between adjacent rooms takes one second for one move and two seconds for the next, alternating between the two.**\nwe can simply have one more state which will store number of moves mode so far so that we can check if even then 1 if odd then 2, rest everything is same , the code goes like\n```\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& mt) {\n int n = mt.size();\n int m = mt[0].size();\n vector<vector<int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n \n \n priority_queue<tuple<int, int, int, int>, vector<tuple<int, int, int, int>>, greater<>> pq;\n pq.push({0, 0, 0, 0});\n \n \n vector<vector<int>> time_taken(n, vector<int>(m, INT_MAX));\n time_taken[0][0] = 0;\n \n while (!pq.empty()) {\n auto [time, x, y, moves_made] = pq.top();\n pq.pop();\n \n if (x == n - 1 && y == m - 1) {\n return time;\n }\n \n for (auto& dir : dirs) {\n int nx = x + dir[0];\n int ny = y + dir[1];\n if (nx >= 0 && nx < n && ny >= 0 && ny < m) {\n \n int move_duration = (moves_made % 2 == 0) ? 1 : 2; \n \n int wait_time = max(time+move_duration, mt[nx][ny] + move_duration);\n \n if (wait_time < time_taken[nx][ny]) {\n time_taken[nx][ny] = wait_time;\n pq.push({wait_time, nx, ny, moves_made + 1});\n }\n }\n }\n }\n \n return -1; \n }\n};\n```\nsince we had one extra constraint we added one more state to check and redefined our edges , everything else remains same.\n\nI have solved CSES graph problems , you can check that out here if you face issues in implementing graph algorithms\nhttps://www.youtube.com/watch?v=6owaCOCWLu0&list=PLQr1KWjS3pAGRjsSp3kcULieEgogfOGj9\n | 1 | 0 | ['C'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra wait till available | dijkstra-wait-till-available-by-theabbie-fgk3 | \nimport heapq\n\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m = len(moveTime)\n n = len(moveTime[0])\n | theabbie | NORMAL | 2024-11-03T04:01:30.899515+00:00 | 2024-11-03T04:01:30.899554+00:00 | 86 | false | ```\nimport heapq\n\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m = len(moveTime)\n n = len(moveTime[0])\n dist = [[float(\'inf\')] * n for _ in range(m)]\n dist[0][0] = 0\n heap = [(0, 0, 0, True)]\n while heap:\n d, i, j, even = heapq.heappop(heap)\n if (i, j) == (m - 1, n - 1):\n return d\n cost = 1 if even else 2\n for x, y in [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]:\n if 0 <= x < m and 0 <= y < n and max(d, moveTime[x][y]) + cost < dist[x][y]:\n dist[x][y] = max(d, moveTime[x][y]) + cost\n heapq.heappush(heap, (dist[x][y], x, y, not even))\n``` | 1 | 0 | ['Python'] | 0 |
find-minimum-time-to-reach-last-room-ii | [Tag: Easy] TEXTBOOK TOGGLY-DIJKSTRA | tag-easy-textbook-toggly-dijkstra-by-tbn-kswl | This is toggly-dijkstra, and a really good question.
For each node i, in the dist array maintain two values
-> dist[i][0] = min dist from src to node i such th | tbne1905 | NORMAL | 2025-04-09T19:01:24.323422+00:00 | 2025-04-09T19:01:24.323422+00:00 | 1 | false | This is toggly-dijkstra, and a really good question.
- For each node i, in the dist array maintain two values
-> dist[i][0] = min dist from src to node i such that landed on i in the first move from its previous node
-> dist[i][1] = min dist from src to node i such that landed on i in the second move from its previous node
- In the minHeap also while doing dijkstra
-> ele.Item1 -> min dist of currNode from src
-> ele.Item2.Item1 -> 0 if we landed on currNode in the first move from its previous node, else 1 if we landed on currNode in the second move from it's previous node
-> ele.Item2.Item2 -> the #node
```csharp []
public class Solution {
int r;
int c;
int[] dX = new int[]{0,0,+1,-1};
int[] dY = new int[]{-1,+1,0,0};
public int MinTimeToReach(int[][] mat) {
r = mat.Length;
c = mat[0].Length;
// ( dist from src, (0/1 where 0 is first move, 1 is second move, node) )
SortedSet<(long, (int, int))> minHeap = new SortedSet<(long, (int, int))>(
Comparer<(long, (int,int))>.Create((a, b) =>
{
int cmp1 = a.Item1.CompareTo(b.Item1);
return cmp1 != 0 ? cmp1 : a.Item2.CompareTo(b.Item2);
})
);
/*
dist[i][0] -> minDist from src to node i such that reached i on first move
dist[i][1] -> minDist from src to node i such that reached i on second move
*/
long[][] dist = new long[r*c][];
for (int i = 0; i < r*c; i++) dist[i] = new long[]{long.MaxValue, long.MaxValue};
dist[0][0] = 0;
dist[0][1] = 0;
minHeap.Add((0,(0,0)));
while(minHeap.Count > 0){
var p = minHeap.Min();
minHeap.Remove(p);
int currNode = p.Item2.Item2;
int moveBit = p.Item2.Item1;
long currDist = p.Item1;
if (currDist > dist[currNode][moveBit]) continue;
int i = currNode / c;
int j = currNode - i * c;
for (int dir = 0; dir < 4; dir++){
int adjI = i + dX[dir];
int adjJ = j + dY[dir];
if (!inBounds(adjI, adjJ)) continue;
int adjNode = getNode(adjI, adjJ);
long weight = 1 + (moveBit * 1) + Math.Max(0, mat[adjI][adjJ]-currDist);
if (currDist + weight >= dist[adjNode][1-moveBit]) continue;
dist[adjNode][1-moveBit] = currDist + weight;
minHeap.Add((dist[adjNode][1-moveBit], (1-moveBit, adjNode)));
}
}
return (int)dist[r*c-1].Min();
}
int getNode(int i, int j){
return i * c + j;
}
bool inBounds(int i, int j){
return i >= 0 && i < r && j >= 0 && j < c;
}
}
``` | 0 | 0 | ['C#'] | 0 |
find-minimum-time-to-reach-last-room-ii | Very Easy To Understand Solution - Just Do Dry Run | very-easy-to-understand-solution-just-do-uncw | Complexity
Time complexity: O(n×m×log(n×m))
Space complexity:O(n×m)
Code | sumamakhan | NORMAL | 2025-03-22T04:31:05.437832+00:00 | 2025-03-22T04:31:05.437832+00:00 | 3 | false | # Complexity
- Time complexity: $$O(n×m×log(n×m))$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(n×m)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
class Node {
int x;
int y;
int time;
int move;
public Node(int x, int y, int time, int move) {
this.x = x;
this.y = y;
this.time = time;
this.move = move;
}
}
public int minTimeToReach(int[][] moveTime) {
int n = moveTime.length;
int m = moveTime[0].length;
int[][] time = new int[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(time[i], Integer.MAX_VALUE);
}
PriorityQueue<Node> pq = new PriorityQueue<>((node1, node2) -> node1.time - node2.time);
pq.add(new Node(0, 0, 0 , 2));
time[0][0] = 0;
while (!pq.isEmpty()) {
Node node = pq.poll();
int x = node.x;
int y = node.y;
int currTime = node.time;
int move = node.move;
if(x == m-1 && y == n -1) return currTime;
int newmove = (move == 1) ? 2 : 1;
int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
for (int[] dir : dirs) {
int nodex = x + dir[0];
int nodey = y + dir[1];
if (nodex >= 0 && nodey >= 0 && nodex < n && nodey < m) {
int newtime = newmove + Math.max(node.time, moveTime[nodex][nodey]);
if (newtime < time[nodex][nodey]) {
time[nodex][nodey] = newtime;
pq.add(new Node(nodex, nodey,newtime, newmove));
}
}
}
}
return time[n-1][m-1];
}
}
``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Very Easy To Understand Solution - Just Do Dry Run | very-easy-to-understand-solution-just-do-sz3b | Code | sumamakhan | NORMAL | 2025-03-22T04:26:58.388504+00:00 | 2025-03-22T04:26:58.388504+00:00 | 2 | false |
# Code
```java []
class Solution {
class Node {
int x;
int y;
int time;
int move;
public Node(int x, int y, int time, int move) {
this.x = x;
this.y = y;
this.time = time;
this.move = move;
}
}
public int minTimeToReach(int[][] moveTime) {
int n = moveTime.length;
int m = moveTime[0].length;
int[][] time = new int[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(time[i], Integer.MAX_VALUE);
}
PriorityQueue<Node> pq = new PriorityQueue<>((node1, node2) -> node1.time - node2.time);
pq.add(new Node(0, 0, 0 , 2));
time[0][0] = 0;
while (!pq.isEmpty()) {
Node node = pq.poll();
int x = node.x;
int y = node.y;
int currTime = node.time;
int move = node.move;
if(x == m-1 && y == n -1) return currTime;
int newmove = (move == 1) ? 2 : 1;
int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
for (int[] dir : dirs) {
int nodex = x + dir[0];
int nodey = y + dir[1];
if (nodex >= 0 && nodey >= 0 && nodex < n && nodey < m) {
int newtime = newmove + Math.max(node.time, moveTime[nodex][nodey]);
if (newtime < time[nodex][nodey]) {
time[nodex][nodey] = newtime;
pq.add(new Node(nodex, nodey,newtime, newmove));
}
}
}
}
return -1;
}
}
``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | C# Solution 64ms | c-solution-64ms-by-slowpuppy-wj7w | IntuitionI will modify this post later.ApproachComplexity
Time complexity:
Space complexity:
Code | Slowpuppy | NORMAL | 2025-03-20T23:41:58.019830+00:00 | 2025-03-20T23:41:58.019830+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
I will modify this post later.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int MinTimeToReach(int[][] moveTime) {
return AnotherVersionBFSSolution(moveTime);
}
private static int M;
private static int N;
private static bool[,] Seen;
private static int[,] Directions = new int[,]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public static int AnotherVersionBFSSolution(int[][] moveTime)
{
if(moveTime == null || moveTime.Length == 0 || moveTime[0] == null || moveTime[0].Length == 0)
{
return 0;
}
M = moveTime.Length;
N = moveTime[0].Length;
if(M == 1 && N == 1)
{
return 0;
}
Seen = new bool[M, N];
// It could be proved take different routes to the same node will end using same odd or even edges
// Because different routes will either share edges or formating circles on the grid
// Circles on the grid always have even number of edges
// Route Length = shareEdge + edges on circle
// Thus final step to one node's odd/even parity is determined
// Thus we only need to check every node once
int[,] finalStep = new int[M, N];
Seen[0, 0] = true;
finalStep[0, 0] = 2;
var timeToPoints = new Dictionary<int, HashSet<(int X, int Y)>>();
PriorityQueue<int, int> timePQ = new PriorityQueue<int, int>();
var end = (M - 1, N - 1);
timePQ.Enqueue(0, 0);
timeToPoints[0] = new HashSet<(int X, int Y)>();
timeToPoints[0].Add((0, 0));
while(timePQ.Count > 0)
{
int currentTime = timePQ.Dequeue();
HashSet<(int X, int Y)> points = timeToPoints[currentTime];
timeToPoints.Remove(currentTime);
foreach(var point in points)
{
int x = point.X;
int y = point.Y;
int nextStep = 3 - finalStep[x, y];
for(int k = 0; k < 4; ++k)
{
int i = x + Directions[k, 0];
int j = y + Directions[k, 1];
if(CouldBeVisited(i, j))
{
Seen[i, j] = true;
finalStep[i, j] = nextStep;
int nextTime = Math.Max(currentTime + nextStep, moveTime[i][j] + nextStep);
if((i, j).Equals(end))
{
return nextTime;
}
if(!timeToPoints.ContainsKey(nextTime))
{
timePQ.Enqueue(nextTime, nextTime);
timeToPoints[nextTime] = new HashSet<(int X, int Y)>();
}
timeToPoints[nextTime].Add((i, j));
}
}
}
}
return -1;
}
private static bool CouldBeVisited(int i, int j)
{
if(i < 0 || i > M -1 || j < 0 || j > N - 1)
{
return false;
}
return !Seen[i, j];
}
}
``` | 0 | 0 | ['C#'] | 0 |
find-minimum-time-to-reach-last-room-ii | easy | easy-by-aj__style20233032-s01c | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Aj__style20233032 | NORMAL | 2025-03-16T19:47:29.150239+00:00 | 2025-03-16T19:47:29.150239+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
int n=moveTime.size();
int m=moveTime[0].size();
vector<vector<int>> dis(n,vector<int>(m,INT_MAX));
dis[0][0]=0;
priority_queue<pair<int,pair<int,pair<int,int>>>,vector<pair<int,pair<int,pair<int,int>>>>,greater<>> pq;
pq.push({0,{2,{0,0}}});
vector<int> row={0,1,0,-1};
vector<int> col={1,0,-1,0};
while(!pq.empty()){
int t=pq.top().first;
int x=pq.top().second.second.first;
int y=pq.top().second.second.second;
int p=pq.top().second.first;
pq.pop();
if(p==1){
p=2;
}
else{
p=1;
}
for(int i=0;i<4;i++){
int nx=x+row[i];
int ny=y+col[i];
int nt;
if(nx>=0 && nx<n && ny>=0 && ny<m ){
if(t>=moveTime[nx][ny] ){
nt=t+p;
}
else {
nt=moveTime[nx][ny]+p;
}
if(nt<dis[nx][ny]){
pq.push({nt,{p,{nx,ny}}});
dis[nx][ny]=nt;
}
}
}
}
return dis[n-1][m-1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Looks like a simple `bfs` would work? Hmm..let's optimize it. | looks-like-a-simple-bfs-would-work-hmmle-m86z | IntuitionLooks like a simple bfs would work? Hmm..let's optimize it.ApproachIf you are at a cell say x with Tx time, you can move to an adjacent cell y with Ty | pratyushtiwarimj | NORMAL | 2025-03-05T15:37:52.479879+00:00 | 2025-03-05T15:37:52.479879+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Looks like a simple `bfs` would work? Hmm..let's optimize it.
# Approach
<!-- Describe your approach to solving the problem. -->
If you are at a cell say `x` with `Tx` time, you can move to an adjacent cell `y` with `Ty` time
with the following cases
1. If you reached early than the required wait time, you will have to wait atleast `Ty`.
2. If reached on time/later than `Ty`, you can move at no cost...apart from the move cost (1 or 2).
[x] -> [y]
So the new time to move from cell [x] to cell [y] would be
```
int newTime = moveCost + max(Tx, Ty);
```
that's it, put this into `bfs` & it will **TLE** :)
Now let's optimize:
Suppose you can reach cell `[x] -> [y] in time 4` via some path, so you update the adjacent cells of `[y]` accordingly and so on. Now suppose you figured out another path you can reach the cell `[x] -> [y] in time 3` (**less than 4**)...now you will have to update all the adjacents of `[y]` again as per the min time of 3, `so the previous updates with time of 4 were of no use`.
We could have avoided it....
One would use a simple `Queue` for `bfs`. But...What is out goal? to get the minimum time to reach any cell from (0, 0) so shouldn't we try to pick the one with the minimum time from the `Queue` first and avoid processing the once if for some node the min reach time is already less than the calculated `newTime`?
So we use `priority_queue(min heap)` instead.
Basically, wou would want to know the path that led to the `time of 3 in reaching [y]` first so you can `avoid the processing as per the time of 4 in reaching [y]`
```
int newTime = add + max(A[xx][yy], time);
if (newTime < minTime[xx][yy]) {
minTime[xx][yy] = newTime;
q.push(Room(xx, yy, newTime, ((add == 1) ? 2 : 1)));
}
```
And ladies & gentleman it's **`Dijkstra’s shortest path algorithm`**
# Complexity
- Time complexity:
For each node you will have 4 neighbours, so complexity: n\*m\*4 ~ `O(n*m)` ...nahh...dont's forget the heap
so it becomes : `O((nm)⋅log(nm))`
- Space complexity:
Size of input: `O(n*m)`
# Code
```cpp []
class Solution {
struct Room {
int x;
int y;
int time;
int add;
Room(int xx, int yy, int ttime, int aadd) {
x = xx;
y = yy;
time = ttime;
add = aadd;
}
};
struct CompareTask {
bool operator()(const Room& t1, const Room& t2) {
return t1.time >
t2.time; // Min-heap (smallest priority first)
}
};
public:
int minTimeToReach(vector<vector<int>>& A) {
int n = A.size();
int m = A[0].size();
vector<vector<int>> minTime(n, vector<int>(m, INT_MAX));
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
priority_queue<Room, vector<Room>, CompareTask> q;
q.push(Room(0, 0, 0, 1));
while (!q.empty()) {
Room top = q.top();
int x = top.x;
int y = top.y;
int time = top.time;
int add = top.add;
q.pop();
for (int i = 0; i < 4; i++) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (xx >= 0 && xx < n && yy >= 0 && yy < m) {
int newTime = add + max(A[xx][yy], time);
if (newTime < minTime[xx][yy]) {
minTime[xx][yy] = newTime;
q.push(Room(xx, yy, newTime, ((add == 1) ? 2 : 1)));
}
}
}
}
return minTime[n - 1][m - 1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | [C++] Priority Queue (Shortest Path) | c-priority-queue-shortest-path-by-amanme-4vib | Code | amanmehara | NORMAL | 2025-03-03T04:59:17.656017+00:00 | 2025-03-03T04:59:17.656017+00:00 | 4 | false | # Code
```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& move_time) {
int n = move_time.size();
int m = move_time[0].size();
vector<vector<int>> min_time(n, vector<int>(m, INT_MAX));
min_time[0][0] = 0;
vector<pair<int, int>> deltas({{-1, 0}, {0, -1}, {1, 0}, {0, 1}});
priority_queue<tuple<int, int, int, int>, vector<tuple<int, int, int, int>>, greater<tuple<int, int, int, int>>> pq;
pq.emplace(0, 0, 0, 1);
while (!pq.empty()) {
auto [pre_time, x, y, pre_dt] = pq.top();
int cur_dt = pre_dt % 2 + 1;
pq.pop();
if (x == n - 1 && y == m - 1) {
return pre_time;
}
for (const auto& [dx, dy]: deltas) {
if (x + dx < 0 || y + dy < 0 || x + dx >= n || y + dy >= m) {
continue;
}
int cur_time = max(pre_time, move_time[x + dx][y + dy]) + pre_dt;
if (min_time[x + dx][y + dy] > cur_time) {
min_time[x + dx][y + dy] = cur_time;
pq.emplace(cur_time, x + dx, y + dy, cur_dt);
}
}
}
return -1;
}
};
``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | CPP||ModifiedDijikastra | cppmodifieddijikastra-by-_shubhambhardwa-27q5 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | _ShubhamBhardwaj_ | NORMAL | 2025-02-27T15:59:00.847411+00:00 | 2025-02-27T15:59:00.847411+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
#include <bits/stdc++.h>
using namespace std;
int x[] = {1, 0, -1, 0};
int y[] = {0, 1, 0, -1};
struct compare {
bool operator()(pair<int, pair<long long, pair<int, int>>> a,
pair<int, pair<long long, pair<int, int>>> b) {
return a.second.first > b.second.first; // Min-heap based on distance
}
};
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
int n = moveTime.size();
int m = moveTime[0].size();
vector<vector<bool>> visited(n, vector<bool>(m, false));
vector<vector<long long>> d(n, vector<long long>(m, LLONG_MAX));
priority_queue<pair<int, pair<long long, pair<int, int>>>,
vector<pair<int, pair<long long, pair<int, int>>>>,
compare> q;
d[0][0] = 0;
q.push({0, {0, {0, 0}}});
while (!q.empty()) {
int parity = q.top().first;
long long dis = q.top().second.first;
int r = q.top().second.second.first;
int c = q.top().second.second.second;
q.pop();
if (r == n - 1 && c == m - 1) {
return dis;
}
// if (visited[r][c]) continue;
// visited[r][c] = true;
for (int i = 0; i < 4; i++) {
int new_row = r + x[i];
int new_col = c + y[i];
if (new_row >= 0 && new_row < n && new_col >= 0 && new_col < m && !visited[new_row][new_col]) {
long long min_time = moveTime[new_row][new_col];
long long addition = (parity % 2 == 0) ? 1 : 2;
// Ensure we reach at least moveTime[new_row][new_col] and align correctly
int newd = max(dis,(long long)1* moveTime[new_row][new_col]) + addition;
if (newd < d[new_row][new_col]) {
d[new_row][new_col] = newd;
q.push(make_pair(parity + 1, make_pair(newd, make_pair(new_row, new_col))));
}
}
}
}
return -1; // If no path is found
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | c++ solution | c-solution-by-amit_207-3qjl | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Amit_207 | NORMAL | 2025-02-22T12:36:40.846362+00:00 | 2025-02-22T12:36:40.846362+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& mat) {
int r = mat.size();
int c = mat[0].size();
vector<vector<int>> d(r, vector<int>(c, INT_MAX));
priority_queue<pair<int, pair<int, int>>,
vector<pair<int, pair<int, int>>>,
greater<pair<int, pair<int, int>>>>
q;
vector<vector<int>> second(r, vector<int>(c, 0));
q.push({0, {0, 0}}); // time, row, column;
d[0][0] = 0;
while (!q.empty()) {
int t = q.top().first;
int i = q.top().second.first;
int j = q.top().second.second;
q.pop();
int val = second[i][j] + 1;
if (i > 0 && max(t, mat[i - 1][j]) + val < d[i - 1][j]) {
d[i - 1][j] = max(t, mat[i - 1][j]) + val;
q.push({d[i - 1][j], {i - 1, j}});
second[i - 1][j] = !(val - 1);
}
if (j < c - 1 && max(t, mat[i][j + 1]) + val < d[i][j + 1]) {
d[i][j + 1] = max(t, mat[i][j + 1]) + val;
q.push({d[i][j + 1], {i, j + 1}});
second[i][j + 1] = !(val - 1);
}
if (i < r - 1 && max(t, mat[i + 1][j]) + val < d[i + 1][j]) {
d[i + 1][j] = max(t, mat[i + 1][j]) + val;
q.push({d[i + 1][j], {i + 1, j}});
second[i + 1][j] = !(val - 1);
}
if (j > 0 && max(t, mat[i][j - 1]) + val < d[i][j - 1]) {
d[i][j - 1] = max(t, mat[i][j - 1]) + val;
q.push({d[i][j - 1], {i, j - 1}});
second[i][j - 1] = !(val - 1);
}
}
return d[r - 1][c - 1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Python3 solution | Dijkstra | python3-solution-dijkstra-by-florinnc1-7qka | IntuitionUsing dijkstra, it's almost identical to3342. Find Minimum Time to Reach Last Room IIand pretty similar to778. Swim in Rising Water.ApproachUse dijkstr | FlorinnC1 | NORMAL | 2025-02-18T20:00:14.968000+00:00 | 2025-02-18T20:00:14.968000+00:00 | 4 | false | # Intuition
Using dijkstra, it's almost identical to $$ $$***3342. Find Minimum Time to Reach Last Room II***$$ $$ and pretty similar to $$ $$***778. Swim in Rising Water***$$ $$.
# Approach
Use dijkstra to maintain the level of time to reach each room. The time to the next adjacent cell will be when parity is 0:
$$distance[(adj_r, adj_c)] = max(current_d + 1, moveTime[adj_row][adj_col] + 1)$$
and when parity is 1:
$$distance[(adj_r, adj_c)] = max(current_d + 2, moveTime[adj_row][adj_col] + 2)$$
We will maintain parity by starting from 0 and switching between 0 and 1 at each cell.
# Complexity
- Time complexity:
$$O((V+E)logV)$$
- Space complexity:
$$O(V+E)$$
# Code
```python3 []
from queue import PriorityQueue
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
distance = defaultdict(lambda: math.inf)
distance[(0, 0)] = 0
queue = PriorityQueue()
queue.put((distance[(0, 0)], 0, 0, 0))
visited = set()
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
n, m = len(moveTime), len(moveTime[0])
while not queue.empty():
# distance, row, column
d, r, c, p = queue.get()
if r == n - 1 and c == m - 1:
return distance[(r, c)]
if (r, c) not in visited:
visited.add((r, c))
for dir in directions:
next_r, next_c = r + dir[0], c + dir[1]
if 0 <= next_r < n and 0 <= next_c < m:
if p == 0:
if distance[(next_r, next_c)] > max(d, moveTime[next_r][next_c] + 1):
distance[(next_r, next_c)] = max(d + 1, moveTime[next_r][next_c] + 1)
else:
if distance[(next_r, next_c)] > max(d + 2, moveTime[next_r][next_c] + 2):
distance[(next_r, next_c)] = max(d + 2, moveTime[next_r][next_c] + 2)
queue.put((distance[(next_r, next_c)], next_r, next_c, (p + 1) % 2))
return distance[(n-1, m-1)]
``` | 0 | 0 | ['Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Shortest Path | Simple Dijkstra's algorithm | shortest-path-simple-dijkstras-algorithm-85l4 | Complexity
Time complexity: O(N x M x log(N x M))
Space complexity: O(N x M)
Code | rohanmathur91 | NORMAL | 2025-02-16T14:12:06.352623+00:00 | 2025-02-16T14:12:06.352623+00:00 | 3 | false | # Complexity
- Time complexity: O(N x M x log(N x M))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N x M)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
"""
- Dijkstra, 4 directions
- constraint: 1sec and 2sec (alternating)
"""
DX = [0, 1, 0, -1]
DY = [-1, 0, 1, 0]
n = len(moveTime)
m = len(moveTime[0])
dist = [[ float(inf) for i in range(m)] for i in range(n)]
vis = [[ 0 for i in range(m)] for i in range(n)]
dist[0][0] = 0
pq = []
heappush(pq, [0, 0, 0, 1]) # time, i, j, alternate cost
while pq:
time, i, j, altTime = heappop(pq)
if vis[i][j] == 1:
continue
vis[i][j] = 1
for k in range(4):
ii = DX[k] + i
jj = DY[k] + j
if 0 <= ii and ii < n and 0 <= jj and jj < m:
cost = altTime
if time < moveTime[ii][jj]:
cost += (moveTime[ii][jj] - time)
nextAltTime = 1 if altTime == 2 else 2
if dist[ii][jj] > dist[i][j] + cost:
dist[ii][jj] = dist[i][j] + cost
heappush(pq, [dist[ii][jj], ii, jj, nextAltTime])
return dist[n-1][m-1]
``` | 0 | 0 | ['Graph', 'Heap (Priority Queue)', 'Shortest Path', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | C++ priority_queue minimal time | c-priority_queue-minimal-time-by-the_ghu-rllz | null | the_ghuly | NORMAL | 2025-02-12T10:47:07.239380+00:00 | 2025-02-12T10:47:07.239380+00:00 | 3 | false | ```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
int m = moveTime.size();
int n = moveTime[0].size();
int dir[5]{0,1,0,-1,0};
vector<vector<bool>> visited(m, vector<bool>(n));
priority_queue<array<int,4>> pq;
pq.push({0,0,0,1});
visited[0][0] = true;
while(!pq.empty()) {
auto curr = std::move(pq.top());
pq.pop();
if ( curr[1]==m-1 && curr[2] == n-1)
return -curr[0];
for(int d = 0; d < 4; ++d)
{
int nx = curr[1]+dir[d];
int ny = curr[2]+dir[d+1];
if(min(nx, ny) >= 0 && nx < m && ny < n && !visited[nx][ny]) {
visited[nx][ny] = true;
pq.push({min(curr[0], -moveTime[nx][ny])-curr[3], nx, ny, 3^curr[3]});
}
}
}
return -1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Simnple dijkstra implementation | simnple-dijkstra-implementation-by-saiku-nnzz | IntuitionDijkstraCode | saikumarkundlapelli | NORMAL | 2025-01-28T16:28:03.860098+00:00 | 2025-01-28T16:28:03.860098+00:00 | 3 | false | # Intuition
Dijkstra
# Code
```cpp []
class Solution {
public:
vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int minTimeToReach(vector<vector<int>>& moveTime) {
int m=moveTime.size();
int n=moveTime[0].size();
priority_queue<tuple<int, int, int, int>, vector<tuple<int, int, int, int>>, greater<tuple<int, int, int, int>>> pq;
vector<vector<int>> time(m, vector<int>(n, INT_MAX));
pq.push({0, 0, 0, 0});
time[0][0]=0;
int value=INT_MAX;
while(!pq.empty()){
auto [t, i, j, flip] = pq.top();
pq.pop();
if(i==m-1 and j==n-1){
value=min(value, t);
}
for(auto d : directions){
int next_i=i+d.first;
int next_j=j+d.second;
if(next_i<0 or next_i>=m or next_j<0 or next_j>=n)continue;
int next_time = max(t, moveTime[next_i][next_j]) + flip%2+1;
if (next_time < time[next_i][next_j]) {
time[next_i][next_j] = next_time;
pq.push({next_time, next_i, next_j, flip%2+1});
}
}
}
return value;
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra's Algorithm/easy. | dijkstras-algorithmeasy-by-rishiinsane-e1c1 | IntuitionApproachTo understand the problem better we can consider moveTime as unlockTime.We move to the cell that unlocks the earliest only then we can reach th | RishiINSANE | NORMAL | 2025-01-23T13:05:50.825243+00:00 | 2025-01-23T13:05:50.825243+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
To understand the problem better we can consider moveTime as unlockTime.We move to the cell that unlocks the earliest only then we can reach the cell `n-1,m-1` in the least possible time. Thus we need access to the cell that unlocks the earliest and we can use a `priority_queue` for the same, and with a slight modification to fill the `time/dist` array we can use the standard `Dijkstra's algorithm`.
We use the formula `2-(nrow+ncol)%2` to get the travelTime based on step (first/second). The formula is derived or based upon the indexes of the cell, for an odd cell use use travelTime=1 and for even cell we use travelTime=2.
# Complexity
- Time complexity:
O((n×m)×log(n×m))
- Space complexity:
O(n×m)
# Code
```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& grid) {
priority_queue<pair<int, pair<int, int>>,
vector<pair<int, pair<int, int>>>, greater<>>
pq;
int n = grid.size(), m = grid[0].size();
//{timeToReachCurrentCell,{i,j}};
pq.push({0, {0, 0}});
vector<vector<int>> time(n, vector<int>(m, -1));
int drow[] = {-1, 0, 1, 0};
int dcol[] = {0, 1, 0, -1};
while (!pq.empty()) {
auto it = pq.top();
pq.pop();
int currtime = it.first;
int crow = it.second.first;
int ccol = it.second.second;
if (crow == n - 1 && ccol == m - 1)
return currtime;
for (int i = 0; i < 4; i++) {
int nrow = crow + drow[i];
int ncol = ccol + dcol[i];
if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m &&
time[nrow][ncol] == -1) {
int travelTime = 2 - (nrow + ncol) % 2;
if (currtime >= grid[nrow][ncol]) {
time[nrow][ncol] = currtime + travelTime;
pq.push({time[nrow][ncol], {nrow, ncol}});
} else {
time[nrow][ncol] = grid[nrow][ncol] + travelTime;
pq.push({time[nrow][ncol], {nrow, ncol}});
}
}
}
}
return -1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Minimum Time to Traverse Grid with Alternating Costs Using Dijkstra's Algorithm using visited array | minimum-time-to-traverse-grid-with-alter-euk5 | IntuitionThe problem requires finding the minimum time to traverse a grid where each cell represents a waiting time, and moves alternate between a cost of 1 and | prashantiiitnag | NORMAL | 2025-01-18T11:21:56.789517+00:00 | 2025-01-18T11:21:56.789517+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires finding the minimum time to traverse a grid where each cell represents a waiting time, and moves alternate between a cost of 1 and 2 units. This can be solved using a modified version of Dijkstra's shortest path algorithm, as it efficiently handles weighted grids.
# Approach
<!-- Describe your approach to solving the problem. -->
State Representation: Each state in the priority queue is represented as (current_time, {x, y, alternating_flag}), where:
current_time is the time taken to reach the current cell.
(x, y) is the current cell position.
alternating_flag indicates whether the next move costs 1 or 2 units.
Priority Queue:
The priority queue ensures that we always process the state with the smallest current_time first.
Push (time, {x, y, flag}) into the queue only if it improves the minimum time for the cell.
Direction Vector:
Use dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}} to represent all four possible directions (up, down, left, right).
Update Mechanism:
For each neighbor (nx, ny) of the current cell (x, y), calculate the new time:
If grid[nx][ny] is less than or equal to current_time, proceed immediately.
Otherwise, wait until grid[nx][ny] and then move.
Visited Array:
Maintain a 2D vis array to ensure cells are not revisited unnecessarily, which optimizes the solution.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n×m×log(n×m))
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n×m)
# Code
```cpp []
class Solution {
#define pip pair<int, pair<bool, pair<int,int>>>
bool isValid(int n, int m, int newX, int newY, vector<vector<bool>>& vis) {
return newX >= 0 && newX < n && newY >= 0 && newY < m && !vis[newX][newY];
}
public:
int minTimeToReach(vector<vector<int>>& mt) {
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int n = mt.size(), m = mt[0].size();
priority_queue<pip, vector<pip>, greater<pip>> pq;
vector<vector<bool>> vis(n, vector<bool>(m, false));
pq.push({0,{true, {0, 0}}});
while (!pq.empty()) {
int x = pq.top().second.second.first;
int y = pq.top().second.second.second;
bool check=pq.top().second.first;
int time = pq.top().first;
pq.pop();
if (x == n - 1 && y == m - 1) {
return time;
}
if (vis[x][y]) continue;
vis[x][y]=true;
for (int i = 0; i < 4; i++) {
int newX = x + dirs[i][0];
int newY = y + dirs[i][1];
if (isValid(n, m, newX, newY, vis)) {
int newTime = mt[newX][newY];
int toAdd = check ? 1 : 2;
if (newTime <= time) {
pq.push({time + toAdd,{!check, {newX, newY}}});
} else {
pq.push({newTime + toAdd,{!check, {newX, newY}}});
}
}
}
}
return -1;
}
};
``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Djiskira's | djiskiras-by-user0782rf-mnnx | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | user0782Rf | NORMAL | 2025-01-16T06:39:44.289765+00:00 | 2025-01-16T06:39:44.289765+00:00 | 3 | false | # Intuition
If the time so far is less than the timeTomove at the current index, then add the difference tot he time so far.
find a way to keep track of what was added last time
heap -> distance, node, previous_appended
distance -> 2d Grid array of how long it took to reach there
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
'''
If the time so far is less than the timeTomove at the current index, then add the difference tot he time so far.
find a way to keep track of what was added last time
heap -> distance, node, previous_appended
distance -> 2d Grid array of how long it took to reach there
'''
distance = [[float('inf')] * len(moveTime[0]) for _ in range(len(moveTime))]
distance[0][0] = moveTime[0][0]
heap = [(0, [0, 0], 2)]
while heap:
distance_, node, previous = heapq.heappop(heap)
if distance_ > distance[node[0]][node[1]]:
continue
for index in [0, 1]:
for adding in [1, -1]:
new_node = list(node)
new_node[index] += adding
row, col = new_node
if index == 0 and row >= len(moveTime) or row < 0:
continue
if index == 1 and col >= len(moveTime[0]) or col < 0:
continue
appending = 1 if previous == 2 else 2
new_distance = distance_ + appending + max(0, moveTime[row][col] - distance_)
if new_distance < distance[row][col]:
distance[new_node[0]][new_node[1]] = new_distance
heappush(heap, (new_distance, new_node, appending))
return distance[-1][-1]
``` | 0 | 0 | ['Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkstra | modified-dijkstra-by-manmapi-mprw | If we start at "odd" position the fee to travel will be 2, and "even" position will fee 1 to travel.Cost to travel to new position will be the maximum value bet | manmapi | NORMAL | 2025-01-15T07:32:12.304385+00:00 | 2025-01-15T07:32:50.447176+00:00 | 4 | false | If we start at "odd" position the fee to travel will be 2, and "even" position will fee 1 to travel.
```Python
fee = 1 + (x + y) % 2
```
Cost to travel to new position will be the maximum value between previous cost + fee or the minimum time + fee
```Python
n_cost = max(A[x_][y_] + fee, cost + fee)
```
The left of code is orginal Dijkstra
# Code
```python3 []
class Solution:
def minTimeToReach(self, A: List[List[int]]) -> int:
n = len(A)
m = len(A[0])
costs = [[float('inf')] * m for _ in range(n)]
costs[0][0] = 0
q = [(0, 0, 0)]
next_ = {(0, 1), (0, -1), (1, 0), (-1, 0)}
while q:
cost,x, y = heapq.heappop(q)
if x == n - 1 and y == m - 1:
return cost
fee = 1 + (x + y) % 2
for i, j in next_:
x_ = x + i
y_ = y + j
if x_ < 0 or x_ >= n or y_ < 0 or y_ >= m:
continue
n_cost = max(A[x_][y_] + fee, cost + fee)
if n_cost < costs[x_][y_]:
heapq.heappush(q, (n_cost, x_, y_))
costs[x_][y_] = n_cost
return costs[-1][-1]
``` | 0 | 0 | ['Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Simple Dijkistra | beginner friendly | simple-dijkistra-beginner-friendly-by-ak-mi2i | Intuitionthis problem was quite itnutive for me just thoughout of reacing next node if we can reach with current distance otherwise wait at that node as well he | akashsuri | NORMAL | 2025-01-13T15:26:53.987957+00:00 | 2025-01-13T15:26:53.987957+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
this problem was quite itnutive for me just thoughout of reacing next node if we can reach with current distance otherwise wait at that node as well here take care of the step and alternate it between the two nodes as well
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
vector<vector<int>> dist(moveTime.size(),vector<int> (moveTime[0].size(),INT_MAX));
priority_queue<pair<int,pair<pair<int,int>,int>>,vector<pair<int,pair<pair<int,int>,int>>>,greater<pair<int,pair<pair<int,int>,int>>>> pq;
pq.push(make_pair(0,make_pair(make_pair(0,0),2)));
dist[0][0]=0;
vector<int> dx={1,0,-1,0};
vector<int> dy={0,1,0,-1};
while(!pq.empty()){
int currx=pq.top().second.first.first;
int curry=pq.top().second.first.second;
int step=pq.top().second.second;
int dst=pq.top().first;
pq.pop();
if(step==1){
step=2;
}else{
step=1;
}
for(int i=0;i<4;i++){
int newx=currx+dx[i];
int newy=curry+dy[i];
if((newx>=0 && newx<moveTime.size()) && (newy>=0 && newy<moveTime[0].size())){
if(moveTime[newx][newy]<=dst){
if(dst+step<dist[newx][newy]){
dist[newx][newy]=dst+step;
pq.push(make_pair(dist[newx][newy],make_pair(make_pair(newx,newy),step)));
}
}else{
if(moveTime[newx][newy]+step<dist[newx][newy]){
dist[newx][newy]=moveTime[newx][newy]+step;
pq.push(make_pair(dist[newx][newy],make_pair(make_pair(newx,newy),step)));
}
}
}
}
}
return dist[moveTime.size()-1][moveTime[0].size()-1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Easy BFS Java solution | easy-bfs-java-solution-by-mayankpathak87-adty | IntuitionThe problem can be likened to a grid-based pathfinding problem where each cell has a cost (represented by moveTime). Our goal is to determine the minim | mayankpathak870 | NORMAL | 2025-01-04T14:00:30.066612+00:00 | 2025-01-04T14:00:30.066612+00:00 | 9 | false | # Intuition
The problem can be likened to a grid-based pathfinding problem where each cell has a cost (represented by moveTime). Our goal is to determine the minimum time it takes to travel from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1).
We are given a matrix, where the time required to move to a neighboring cell is not uniform, and the movement rules alternate between two states, controlled by the oddEven flag. This means that the behavior of moving from one cell to another can change depending on whether the current state is "odd" or "even."
# Approach
Grid Representation:
Treat the grid as a weighted graph where each cell (i, j) represents a node, and the edges between them represent the movement to neighboring cells.
The cost of each move from one cell to another is determined by the moveTime matrix, which stores the time required to enter each cell.
Priority Queue:
Use a Priority Queue (Min-Heap) to always explore the cell with the smallest accumulated time first. This is essential for Dijkstra's algorithm.
Each element in the queue will store the current position (i, j) of the cell, the accumulated time (weight), and the current state of oddEven flag, which alternates between 1 and 2.
State Transition:
The oddEven flag alternates with each move, which may modify the cost calculation. Specifically, this flag determines the movement time: if oddEven is 1, then the movement time might be computed differently than when it's 2.
The flag is toggled every time a cell is processed to switch between two different movement behaviors.
Traversal:
Start from the top-left corner (0, 0). For each cell, explore its neighbors (up, down, left, right), calculate the new potential cost to reach each neighbor, and update the priority queue accordingly.
If the new cost to reach a neighboring cell is smaller than the current stored value, update the cell's value and push the new state into the queue.
End Condition:
If we reach the bottom-right corner (m-1, n-1), return the accumulated time.
Edge Case:
The algorithm should handle situations where the destination is unreachable, though in the problem setup, it's assumed that the destination is reachable (since it is a valid grid).
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int minTimeToReach(int[][] moveTime) {
int m = moveTime.length;
int n = moveTime[0].length;
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a->a[2]));
int matrix[][] = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
matrix[i][j] = Integer.MAX_VALUE;
}
}
matrix[0][0] =0;
pq.offer(new int[]{0,0,0,1});
int delrow [] = new int[]{-1,0,1,0};
int delcol [] = new int[]{0,1,0,-1};
while(!pq.isEmpty()){
int curr[] = pq.poll();
int row = curr[0];
int col = curr[1];
int weight = curr[2];
int oddEven = curr[3];
if(row==m-1 && col==n-1){
return weight;
}
for(int i=0;i<4;i++){
int nrow = row+delrow[i];
int ncol = col+delcol[i];
if(nrow>=0 && ncol>=0 && nrow<m && ncol<n){
int currtime = Math.max(0,moveTime[nrow][ncol]-weight);
int newWeight = oddEven+currtime+weight;
if(newWeight<matrix[nrow][ncol]){
matrix[nrow][ncol] = newWeight;
if(oddEven==1){
pq.offer(new int[]{nrow,ncol,newWeight,2});
}else{
pq.offer(new int[]{nrow,ncol,newWeight,1});
}
}
}
}
}
return -1;
}
}
``` | 0 | 0 | ['Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Using PriorityQueue, Beats 61% | using-priorityqueue-beats-61-by-poshis-h20a | IntuitionApproachComplexity
Time complexity: O(m∗n∗log(m∗n))
Space complexity: O(m∗n)
Code | poshis | NORMAL | 2024-12-28T08:02:13.127914+00:00 | 2024-12-28T08:02:13.127914+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(m∗n∗log(m∗n))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(m∗n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int MinTimeToReach(int[][] moveTime) {
int m = moveTime.Length;
int n = moveTime[0].Length;
int[][] minArray = new int[m][];
for (int i = 0; i < m; i++)
{
minArray[i] = Enumerable.Repeat(int.MaxValue, n).ToArray();
}
//row col time
PriorityQueue<(int, int), int> pq = new();
HashSet<(int, int)> set = new HashSet<(int, int)>();
minArray[0][0] = 0;
pq.Enqueue((0,0), 0);
int[][] directions = new int[][]
{
[0,1], [0,-1], [1,0], [-1,0]
};
while (pq.Count > 0)
{
if (pq.TryDequeue(out var temp, out int _))
{
int row = temp.Item1;
int col = temp.Item2;
if(row == m-1 && col == n - 1)
{
return minArray[m - 1][n - 1];
}
int currentStep = (row + col) %2 == 0 ? 1 : 2;
if (set.Contains((row, col)))
{
continue;
}
else
{
set.Add((row, col));
}
foreach (var ar in directions)
{
int x = row + ar[0];
int y = col + ar[1];
if (x >= 0 && y >= 0 && x < m && y < n)
{
int time = 0;
if (moveTime[x][y] <= minArray[row][col])
{
time = minArray[row][col] + currentStep;
}
else
{
time = moveTime[x][y] + currentStep;
}
if (time < minArray[x][y])
{
pq.Enqueue((x, y), time);
minArray[x][y] = Math.Min(minArray[x][y], time);
}
}
}
}
}
return minArray[m - 1][n - 1];
}
}
``` | 0 | 0 | ['C#'] | 0 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkstra's | modified-dijkstras-by-nraghav5-5rxs | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | nraghav5 | NORMAL | 2024-12-25T06:17:14.968351+00:00 | 2024-12-25T06:17:14.968351+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
priority_queue<pair<int,pair<int,pair<int,int>>>,
vector<pair<int, pair<int,pair<int,int>>>>,
greater<pair<int,pair<int,pair<int,int>>>>>pq;
pq.push({0,{0,{0,0}}}) ;
int n = moveTime.size() ;
int m = moveTime[0].size() ;
vector<vector<int>>time(n,vector<int>(m,INT_MAX));
time[0][0]=0;
int drow[]={1,0,-1,0} ;
int dcol[] = {0,-1,0,1} ;
while(!pq.empty()){
int row = pq.top().second.second.first;
int col = pq.top().second.second.second;
int turn = pq.top().second.first;
int t = pq.top().first;
pq.pop() ;
if(row==n-1 &&col==m-1)return t;
for(int i=0; i<4; i++){
int nrow =row+drow[i] ;
int ncol = col+dcol[i] ;
if(nrow<n && nrow>=0 && ncol<m && ncol>=0){
if(turn==0){
if(moveTime[nrow][ncol]>t){
if(time[nrow][ncol]>moveTime[nrow][ncol]+1){
time[nrow][ncol]=moveTime[nrow][ncol]+1;
pq.push({moveTime[nrow][ncol]+1, {!turn, {nrow,ncol}}});
}
}
else{
if(time[nrow][ncol]>t+1){
time[nrow][ncol]=t+1;
pq.push({t+1, {!turn, {nrow,ncol}}}) ;
}
}
}
else{
if(moveTime[nrow][ncol]>t){
if(time[nrow][ncol]>moveTime[nrow][ncol]+2){
time[nrow][ncol]=moveTime[nrow][ncol]+2;
pq.push({moveTime[nrow][ncol]+2, {!turn, {nrow,ncol}}});
}
}
else{
if(time[nrow][ncol]>t+2){
time[nrow][ncol]=t+2;
pq.push({t+2, {!turn, {nrow,ncol}}}) ;
}
}
}
}
}
}
return time[n-1][m-1] ;
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkstra Algorithm | Beats 96% | modified-dijkstra-algorithm-beats-96-by-8n3lt | Code | adityasharma00070 | NORMAL | 2024-12-18T08:45:29.159195+00:00 | 2024-12-18T08:45:29.159195+00:00 | 5 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& grid) {\n int n=grid.size(),m=grid[0].size();\n priority_queue<pair<int,pair<bool,pair<int,int>>>,vector<pair<int,pair<bool,pair<int,int>>>>,greater<pair<int,pair<bool,pair<int,int>>>>>pq;\n vector<vector<bool>>vis(n,vector<bool>(m,false));\n //false =1 true=2\n pq.push({0,{false,{0,0}}});\n vis[0][0]=true;\n vector<int>drow={-1,0,1,0},dcol={0,1,0,-1};\n while(pq.empty()==false){\n int time=pq.top().first;\n bool mode=pq.top().second.first;\n int row=pq.top().second.second.first;\n int col=pq.top().second.second.second;\n if(row==n-1 && col==m-1) return time;\n pq.pop();\n for(int i=0; i<4; i++){\n int nrow=row+drow[i],ncol=col+dcol[i];\n if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && vis[nrow][ncol]==false){\n if(grid[nrow][ncol]<=time){\n pq.push({mode==false?time+1:time+2,{!mode,{nrow,ncol}}});\n vis[nrow][ncol]=true;\n }\n else{\n pq.push({mode==false?grid[nrow][ncol]+1:grid[nrow][ncol]+2,{!mode,{nrow,ncol}}});\n vis[nrow][ncol]=true;\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | C++ || Easy Implementation | c-easy-implementation-by-james_thorn-m7fd | It is just like number of Islands problem using BFS but you have to use priority queue or min heap for the accomodation of weight (time here) and add some more | james_thorn | NORMAL | 2024-12-15T11:02:14.172058+00:00 | 2024-12-15T11:02:14.172058+00:00 | 3 | false | It is just like number of Islands problem using BFS but you have to use priority queue or min heap for the accomodation of weight (time here) and add some more conditions\n\n\n# Complexity\n- Time complexity: O(N * M)log(N * M)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N*M)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int dx[4] = {0,1,0,-1};\n int dy[4] = {1,0,-1,0};\n\n int minTimeToReach(vector<vector<int>>& movetime) {\n int rows = movetime.size();\n int cols = movetime[0].size();\n\n vector<vector<int>> time(rows,vector<int>(cols,INT_MAX));\n time[0][0] = 0;\n\n priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;\n pq.push({0,0,0,0});\n\n while(!pq.empty())\n {\n int curr = pq.top()[0];\n int x = pq.top()[1];\n int y = pq.top()[2];\n int flag = pq.top()[3];\n pq.pop();\n\n if(x == rows-1 && y == cols-1) return time[x][y];\n\n for(int i=0; i<4; i++)\n {\n int a = x + dx[i];\n int b = y + dy[i];\n\n if(a>=0 && a<rows && b>=0 && b<cols)\n {\n int diff = INT_MAX;\n\n if(flag == 0) diff = max(curr,movetime[a][b]) + 1;\n else diff = max(curr,movetime[a][b]) + 2;\n\n if(time[a][b] > diff)\n {\n time[a][b] = diff;\n if(flag == 0) pq.push({diff,a,b,1});\n else if(flag == 1) pq.push({diff,a,b,0});\n }\n \n }\n }\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | C++ | Dijkstra on Grid | Easy to understand | c-dijkstra-on-grid-easy-to-understand-by-hqoq | Code\ncpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n=moveTime.size();\n int m=moveTime[0].size | nroutray | NORMAL | 2024-12-04T01:17:52.574909+00:00 | 2024-12-04T01:17:52.574935+00:00 | 5 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n=moveTime.size();\n int m=moveTime[0].size();\n vector<pair<int,int>> dir={{0,1},{1,0},{-1,0},{0,-1}};\n priority_queue< pair<pair<int,int>, pair<int,int>>, vector<pair<pair<int,int>, pair<int,int>>>, greater<pair<pair<int,int>, pair<int,int>>> > pq;\n vector<vector<int>> dist(n, vector<int>(m,INT_MAX));\n dist[0][0]=0;\n pq.push({{0,1},{0,0}});\n\n while(!pq.empty()){\n int time=pq.top().first.first;\n int addTime=pq.top().first.second;\n int r=pq.top().second.first;\n int c=pq.top().second.second;\n pq.pop();\n\n for(int i=0;i<4;i++){\n int nr=r+dir[i].first;\n int nc=c+dir[i].second;\n if(nr>=0 && nr<n && nc>=0 &&nc<m){\n if(time>=moveTime[nr][nc] && time+addTime<dist[nr][nc]){\n dist[nr][nc]=time+addTime;\n if(addTime==1) pq.push({{dist[nr][nc],2},{nr,nc}});\n else pq.push({{dist[nr][nc],1},{nr,nc}}); \n }else if(time<moveTime[nr][nc] && moveTime[nr][nc]+addTime<dist[nr][nc]){\n dist[nr][nc]=moveTime[nr][nc]+addTime;\n if(addTime==1) pq.push({{dist[nr][nc],2},{nr,nc}});\n else pq.push({{dist[nr][nc],1},{nr,nc}});\n }\n }\n }\n }\n\n\n return dist[n-1][m-1];\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | via Priority Queue | via-priority-queue-by-mansoorafzal-kxcg | Complexity\n- Time complexity:\nO((n * m).log(n * m))\n\n- Space complexity:\nO(n * m)\n\n# Code\ncsharp []\npublic class Solution {\n public int MinTimeToRe | mansoorafzal | NORMAL | 2024-11-29T17:01:48.065616+00:00 | 2024-11-29T17:01:48.065663+00:00 | 6 | false | # Complexity\n- Time complexity:\n$$O((n * m).log(n * m))$$\n\n- Space complexity:\n$$O(n * m)$$\n\n# Code\n```csharp []\npublic class Solution {\n public int MinTimeToReach(int[][] moveTime) {\n int n = moveTime.Length;\n int m = moveTime[0].Length;\n\n HashSet<(int, int)> directions = new HashSet<(int, int)>() { (1, 0), (-1, 0), (0, 1), (0, -1) };\n PriorityQueue<(int, int, int, int), int> queue = new PriorityQueue<(int, int, int, int), int>();\n HashSet<(int, int)> visited = new HashSet<(int, int)>();\n\n queue.Enqueue((0, 0, 0, 0), 0);\n visited.Add((0, 0));\n\n while (queue.Count > 0) {\n var (x, y, time, last) = queue.Dequeue();\n \n if (x == n - 1 && y == m - 1) {\n return time;\n }\n\n if (last == 1) {\n last = 2;\n }\n else {\n last = 1;\n }\n\n foreach (var (dx, dy) in directions) {\n int newX = x + dx;\n int newY = y + dy;\n\n if (newX < 0 || newX >= n || newY < 0 || newY >= m) {\n continue;\n }\n\n if (visited.Contains((newX, newY))) {\n continue;\n }\n\n int next = Math.Max(time, moveTime[newX][newY]) + last;\n\n queue.Enqueue((newX, newY, next, last), next);\n visited.Add((newX, newY));\n }\n }\n\n return -1;\n }\n}\n``` | 0 | 0 | ['Graph', 'Heap (Priority Queue)', 'Shortest Path', 'C#'] | 0 |
find-minimum-time-to-reach-last-room-ii | Minimum Time To Reach Last Room II !100% Beat CPP | minimum-time-to-reach-last-room-ii-100-b-gyry | Intuition\n\nThe problem at hand seems to be a pathfinding challenge where you need to calculate the minimum time to traverse a grid, starting from the top-left | Gopi_C_K | NORMAL | 2024-11-29T13:03:13.044667+00:00 | 2024-11-29T13:03:13.044708+00:00 | 6 | false | ### Intuition\n\nThe problem at hand seems to be a pathfinding challenge where you need to calculate the minimum time to traverse a grid, starting from the top-left corner `(0, 0)` and ending at the bottom-right corner `(m-1, n-1)`. Each cell in the grid has a "time" value that could affect your movement through it. The grid might involve alternating movement times (e.g., even steps could take 1 second, odd steps could take 2 seconds) and may require you to wait at certain cells until a specific time. A **priority queue** can be used to explore cells in order of the least time taken to reach them, which is similar to Dijkstra\u2019s shortest path algorithm, with slight modifications to account for the alternating time and waiting periods.\n\n### Approach\n\n1. **Grid Representation**: \n - The grid is a 2D vector where each element contains a value that represents a "time" or some kind of condition to move through that cell.\n \n2. **Priority Queue for Efficient Pathfinding**:\n - Use a **priority queue** (min-heap) to process the cells in order of the least time required to reach them. This is akin to Dijkstra\u2019s algorithm where we always process the current shortest time first.\n - The priority queue stores tuples of `(step, time, cell)`, where:\n - `step` indicates whether we are in an even or odd step (affecting movement time).\n - `time` is the current time at the cell.\n - `cell` is the linearized position of the grid (to easily handle 2D grid access).\n \n3. **Movement Calculation**:\n - The four possible directions are represented by a list of pairs `directions = [(1,0), (0,1), (-1,0), (0,-1)]`.\n - Each direction corresponds to a movement in the grid (right, down, left, up).\n\n4. **State Updates**:\n - For each neighboring cell, compute the new time considering:\n - The current time (whether it\'s even or odd step).\n - Whether we need to wait (if the current time is less than the grid value at the neighbor).\n - The movement time, which alternates between 1 and 2 seconds based on the `step`.\n\n5. **Priority Queue Push**:\n - If a new time for a neighboring cell is better (smaller) than the previously recorded time, update the time and push the new state (updated time, step, position) into the priority queue.\n\n6. **Termination**:\n - The process continues until we reach the destination cell `(m-1, n-1)`, and the corresponding time is returned.\n\n### Complexity\n\n- **Time complexity**:\n - The algorithm is based on Dijkstra\u2019s shortest path, so the time complexity is proportional to the number of cells (nodes) in the grid and the number of edges (possible directions).\n - Since we use a priority queue, each insertion and extraction takes logarithmic time.\n - Therefore, the time complexity is **O((m * n) * log(m * n))**, where `m * n` is the number of cells in the grid.\n\n- **Space complexity**:\n - We maintain a `time` 2D array to track the minimum time to reach each cell, and we use a priority queue that stores each cell at least once.\n - The space complexity is **O(m * n)** for the `time` array and the priority queue.\n\n### Code Explanation\n\n```cpp\nauto speedUp = []() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return 0;\n}();\n#define p pair< int, pair<int,int> > // {step {time, cell}}\n```\n- This snippet optimizes input/output operations to make the program run faster for larger inputs.\n- The macro `p` defines a tuple type to represent a state in the priority queue: `{step, {time, cell}}`.\n\n---\n\n```cpp\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n```\n- Here, `m` and `n` represent the number of rows and columns in the grid.\n\n---\n\n```cpp\n vector<pair<int,int>> directions = { {1,0}, {0,1}, {-1,0}, {0,-1} };\n```\n- This vector stores the four possible directions (right, down, left, up) for movement in the grid.\n\n---\n\n```cpp\n vector<vector<int>> time(m, vector<int>(n, INT_MAX));\n time[0][0] = 0;\n```\n- The `time` array keeps track of the minimum time required to reach each cell.\n- We initialize all cells with `INT_MAX` (infinity), except for the starting cell `(0, 0)` which is set to `0` because no time is required to be there initially.\n\n---\n\n```cpp\n priority_queue<p, vector<p>, greater<p>> pq;\n pq.push({0, {0, 0}});\n```\n- We initialize the priority queue `pq` which will store states in the form of `(step, {time, cell})`. We push the starting cell `(0,0)` with time `0`.\n\n---\n\n```cpp\n while (!pq.empty()) {\n p top = pq.top();\n pq.pop();\n int step = top.first;\n int curr_time = top.second.first;\n int row = top.second.second / n;\n int col = top.second.second % n;\n```\n- The main loop processes the room with the least time, popping it from the priority queue.\n- We extract `step`, `curr_time`, `row`, and `col` from the current state.\n\n---\n\n```cpp\n if (row == m - 1 && col == n - 1) \n return curr_time;\n```\n- If we reach the bottom-right corner, we return the current time as the result.\n\n---\n\n```cpp\n for (auto& dir : directions) {\n int nr = row + dir.first;\n int nc = col + dir.second;\n if (nr < 0 || nr >= m || nc < 0 || nc >= n) \n continue;\n```\n- We iterate over the four possible directions to move to the neighboring cells.\n- If the new position is out of bounds, we skip it.\n\n---\n\n```cpp\n // Calculate the next time\n int move_time = curr_time % 2 == 0 ? 1 : 2; // Alternates: 1s -> 2s\n int wait_time = max(0, grid[nr][nc] - curr_time);\n int new_time = curr_time + move_time + wait_time;\n```\n- We calculate the `move_time` based on whether the current time is even or odd.\n- The `wait_time` is calculated if the current time is less than the grid value at the neighboring cell, meaning we need to wait for the appropriate time to move there.\n\n---\n\n```cpp\n if (new_time < time[nr][nc]) {\n time[nr][nc] = new_time;\n pq.push({step == 0 ? 1 : 0, {new_time, nr * n + nc}});\n }\n }\n return -1;\n }\n};\n```\n- If the `new_time` to reach the neighboring cell is better than the previously stored time, we update the `time` array and push the new state into the priority queue with the updated `step` and `time`.\n\n- If the queue is exhausted without reaching the destination, we return `-1` as a fallback.\n\n---\n### Code\n```cpp []\nauto speedUp = []() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return 0;\n}();\n#define p pair< int, pair<int,int> >\n\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n\n vector<pair<int,int>> directions = { {1,0}, {0,1}, {-1,0}, {0,-1} };\n\n vector<vector<int>> time(m, vector<int> (n, INT_MAX));\n time[0][0] = 0;\n\n priority_queue< p, vector<p>, greater<p> > pq;\n pq.push({0, {0,0}}); // {step, time, cell}\n\n while(!pq.empty()){\n p top = pq.top();\n pq.pop();\n int step = top.first;\n int curr_time = top.second.first;\n int row = top.second.second / n;\n int col = top.second.second % n;\n\n if(row == m-1 && col == n-1) return curr_time;\n for(auto &dir : directions){\n int nr = row + dir.first;\n int nc = col + dir.second;\n\n if( nr == -1 || nr == m || nc == -1 || nc == n ) continue;\n int new_time;\n\n if(step == 0){\n if(curr_time >= grid[nr][nc]) new_time = curr_time + 1;\n else new_time = grid[nr][nc] + 1;\n }else{\n if(curr_time >= grid[nr][nc]) new_time = curr_time + 2;\n else new_time = grid[nr][nc] + 2;\n }\n \n if(new_time < time[nr][nc]){\n time[nr][nc] = new_time;\n pq.push({step==0 ? 1 : 0, {new_time, nr*n + nc}});\n }\n }\n }\n return -1; \n }\n};\n```\n### Conclusion\n\nThis approach effectively uses a modified Dijkstra\'s algorithm with a priority queue to find the minimum time to reach the bottom-right corner of the grid, considering alternating movement times and potential wait times at certain cells. The time and space complexities are optimal for this type of problem. | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Easy Djikstra solution | easy-djikstra-solution-by-pipilongstocki-ax4u | Code\npython3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m, n = len(moveTime), len(moveTime[0])\n dirs | pipilongstocking | NORMAL | 2024-11-29T09:31:23.686946+00:00 | 2024-11-29T09:31:23.686985+00:00 | 4 | false | # Code\n```python3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m, n = len(moveTime), len(moveTime[0])\n dirs = [[1,0],[-1,0],[0,1],[0,-1]]\n times = [[inf] * n for _ in range(m)]\n times[0][0] = 0\n min_heap = [[0, 0, 0, 1]]\n\n while min_heap:\n steps_taken, x, y, steps = heappop(min_heap)\n # at what time we could have moves to x, y\n if x == m-1 and y == n-1:\n return steps_taken\n for dx, dy in dirs:\n tx, ty = x+dx, y+dy\n if 0 <= tx < m and 0 <= ty < n:\n # time taken to move to this cell\n ssteps_taken = steps_taken + steps+max(moveTime[tx][ty]-times[x][y], 0)\n if ssteps_taken < times[tx][ty]:\n heappush( min_heap, [ssteps_taken, tx, ty, (steps%2)+1] )\n times[tx][ty] = ssteps_taken\n return times[m-1][n-1]\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Shortest Path', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Solved using modified Dijkstra's algorithm in cpp beating 98 % solutions. | solved-using-modified-dijkstras-algorith-7jzg | Intuition\nThe given solution uses a priority queue to implement a modified Dijkstra\'s algorithm for finding the minimum time to reach the bottom-right corner | ankitsharma1145 | NORMAL | 2024-11-29T07:33:11.480182+00:00 | 2024-11-29T07:33:11.480207+00:00 | 5 | false | # Intuition\nThe given solution uses a priority queue to implement a modified Dijkstra\'s algorithm for finding the minimum time to reach the bottom-right corner of a grid, where the time taken to move depends on the number of steps taken.\n\n\n# Complexity\n- Time complexity:\n1. The algorithm processes each cell in the grid at most once. Since there are n * m cells in the grid, the worst-case scenario involves visiting each cell.\n2. For each cell, the algorithm checks its four possible neighbors (up, down, left, right). This results in a constant factor of 4 for each cell.\n3. The priority queue operations (insertion and extraction) take O(log(k)), where k is the number of elements in the queue. In the worst case, k can be up to n * m, leading to O(log(n * m)) for each operation.\n4. Therefore, the overall time complexity can be expressed as O((n * m) * log(n * m)).\n\n- Space complexity:\n1. The space used for the priority queue can grow up to O(n * m) in the worst case, as it may store entries for each cell.\n2. The `visited` array also takes O(n * m) space to keep track of the minimum time to reach each cell.\n3. Thus, the overall space complexity is O(n * m).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size();\n int m = moveTime[0].size();\n priority_queue<pair<int,pair<int,pair<int,int>>>, vector<pair<int,pair<int,pair<int,int>>>> , greater<pair<int,pair<int,pair<int,int>>>>> pq;\n vector<vector<int>> visited(n,vector<int>(m,INT_MAX));\n visited[0][0] = 0;\n pq.push({0,{0,{0,0}}});\n vector<int> drow = {-1,0,1,0};\n vector<int> dcol = {0,1,0,-1};\n while(!pq.empty()){\n auto [time,steps_pos] = pq.top();\n pq.pop();\n auto[steps , pos] = steps_pos;\n auto[x,y] = pos;\n if(x == n-1 && y == m-1) return time;\n for(int i =0;i<4;i++){\n int nx = x + drow[i];\n int ny = y + dcol[i];\n if(nx>=0 && nx<n && ny>=0 && ny<m){\n int newTime;\n if(steps %2 == 0){\n newTime = max(time,moveTime[nx][ny])+1;\n }\n else newTime = max(time,moveTime[nx][ny]) +2;\n if(newTime < visited[nx][ny]){\n visited[nx][ny] = newTime;\n pq.push({visited[nx][ny],{steps+1,{nx,ny}}});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Python | C++ Dijkstra | python-c-dijkstra-by-kaluginpeter-9wqr | \n\n# Complexity\n- Time complexity: O(ElogE)\n\n- Space complexity: O(ElogE)\n\n# Code\npython []\nclass Solution:\n def minTimeToReach(self, moveTime: List | kaluginpeter | NORMAL | 2024-11-26T17:46:05.779294+00:00 | 2024-11-26T17:46:05.779335+00:00 | 0 | false | \n\n# Complexity\n- Time complexity: O(ElogE)\n\n- Space complexity: O(ElogE)\n\n# Code\n```python []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n m, n = len(moveTime), len(moveTime[0])\n pq: list[tuple[int]] = [(0, 0, 0, 0)]\n min_time: list[list[int]] = [[float(\'inf\')] * n for _ in range(m)]\n min_time[0][0] = 0\n directions: list[tuple[int]] = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n while pq:\n curr_time, r, c, is_extra = heapq.heappop(pq)\n if r == m - 1 and c == n - 1:\n return max(curr_time, moveTime[r][c])\n\n if curr_time > min_time[r][c]:\n continue\n \n for dr, dc in directions:\n nr, nc = r + dr, c + dc\n if 0 <= nr < m and 0 <= nc < n:\n next_time = max(curr_time, moveTime[nr][nc]) + [1, 2][is_extra]\n if next_time < min_time[nr][nc]:\n min_time[nr][nc] = next_time\n heapq.heappush(pq, (next_time, nr, nc, ~is_extra))\n return -1\n```\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m = moveTime.size();\n int n = moveTime[0].size();\n std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, std::greater<std::vector<int>>> pq;\n pq.push({0, 0, 0, 0});\n std::vector<std::vector<int>> minTime(m, std::vector<int>(n, 1100000000));\n std::vector<std::pair<int, int>> directions = {\n {0, 1}, {0, -1}, {1, 0}, {-1, 0}\n };\n while (pq.size()) {\n int currentTime = pq.top()[0];\n int currentRow = pq.top()[1];\n int currentCol = pq.top()[2];\n bool isExtra = pq.top()[3];\n pq.pop();\n if (currentRow == m - 1 && currentCol == n - 1) {\n return std::max(currentTime, moveTime[m - 1][n - 1]);\n }\n if (currentTime >= minTime[currentRow][currentCol]) {\n continue;\n }\n minTime[currentRow][currentCol] = currentTime;\n for (std::pair<int, int> direction : directions) {\n int nextRow = currentRow + direction.first;\n int nextCol = currentCol + direction.second;\n \n if (0 <= std::min(nextRow, nextCol) && nextRow < m && nextCol < n) {\n int nextTime = std::max(currentTime, moveTime[nextRow][nextCol]) + (isExtra? 2 : 1);\n pq.push({nextTime, nextRow, nextCol, !isExtra});\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Java | JavaScript | TypeScript | C++ | C# | Kotlin | Go Solution. | java-javascript-typescript-c-c-kotlin-go-926p | Java []\nimport java.util.Arrays;\nimport java.util.PriorityQueue;\n\npublic class Solution {\n\n private record Step(int row, int column, int timeToMoveBetw | LachezarTsK | NORMAL | 2024-11-25T05:21:39.908502+00:00 | 2024-11-25T05:26:43.192835+00:00 | 10 | false | ```Java []\nimport java.util.Arrays;\nimport java.util.PriorityQueue;\n\npublic class Solution {\n\n private record Step(int row, int column, int timeToMoveBetweenTwoPoints, int timeFromStart) {}\n\n private static final int[] UP = {-1, 0};\n private static final int[] DOWN = {1, 0};\n private static final int[] LEFT = {0, -1};\n private static final int[] RIGHT = {0, 1};\n private static final int[][] MOVES = {UP, DOWN, LEFT, RIGHT};\n\n private int rows;\n private int columns;\n\n private int startRow;\n private int startColumn;\n\n private int targetRow;\n private int targetColumn;\n\n public int minTimeToReach(int[][] moveTime) {\n rows = moveTime.length;\n columns = moveTime[0].length;\n\n startRow = 0;\n startColumn = 0;\n\n targetRow = rows - 1;\n targetColumn = columns - 1;\n\n return dijkstraSearchForPathWithMinTime(moveTime);\n }\n\n private int dijkstraSearchForPathWithMinTime(int[][] moveTime) {\n PriorityQueue<Step> minHeapForTime = new PriorityQueue<>((x, y) -> x.timeFromStart - y.timeFromStart);\n minHeapForTime.add(new Step(startRow, startColumn, 0, 0));\n\n int[][] minTimeMatrix = new int[rows][columns];\n for (int row = 0; row < rows; ++row) {\n Arrays.fill(minTimeMatrix[row], Integer.MAX_VALUE);\n }\n minTimeMatrix[startRow][startColumn] = 0;\n\n while (!minHeapForTime.isEmpty()) {\n Step current = minHeapForTime.poll();\n if (current.row == targetRow && current.column == targetColumn) {\n break;\n }\n\n for (int[] move : MOVES) {\n int nextRow = current.row + move[0];\n int nextColumn = current.column + move[1];\n if (!isInMatrix(nextRow, nextColumn)) {\n continue;\n }\n\n int timeToMoveToNextPoint = getNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints);\n int nextValueForTime = Math.max(timeToMoveToNextPoint + current.timeFromStart,\n timeToMoveToNextPoint + moveTime[nextRow][nextColumn]);\n\n if (minTimeMatrix[nextRow][nextColumn] > nextValueForTime) {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime;\n minHeapForTime.add(new Step(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime));\n }\n }\n }\n\n return minTimeMatrix[targetRow][targetColumn];\n }\n\n private boolean isInMatrix(int row, int column) {\n return row >= 0 && row < rows && column >= 0 && column < columns;\n }\n\n private int getNewTimeToMoveBetweenTwoPoints(int prviousTimeToMoveBetweenTwoPoints) {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2);\n }\n}\n```\n```JavaScript []\n/**\n * @param {number[][]} moveTime\n * @return {number}\n */\nvar minTimeToReach = function (moveTime) {\n const UP = [-1, 0];\n const DOWN = [1, 0];\n const LEFT = [0, -1];\n const RIGHT = [0, 1];\n\n this.MOVES = [UP, DOWN, LEFT, RIGHT];\n\n this.rows = moveTime.length;\n this.columns = moveTime[0].length;\n\n this.startRow = 0;\n this.startColumn = 0;\n\n this.targetRow = this.rows - 1;\n this.targetColumn = this.columns - 1;\n\n return dijkstraSearchForPathWithMinTime(moveTime);\n};\n\n/**\n * @param {number} row\n * @param {number} column\n * @param {number} timeToMoveBetweenTwoPoints \n * @param {number} timeFromStart\n */\nfunction Step(row, column, timeToMoveBetweenTwoPoints, timeFromStart) {\n this.row = row;\n this.column = column;\n this.timeToMoveBetweenTwoPoints = timeToMoveBetweenTwoPoints;\n this.timeFromStart = timeFromStart;\n}\n\n/**\n * @param {number[][]} moveTime\n * @return {number}\n */\nfunction dijkstraSearchForPathWithMinTime(moveTime) {\n const minHeapForTime = new MinPriorityQueue({compare: (x, y) => x.timeFromStart - y.timeFromStart});\n minHeapForTime.enqueue(new Step(this.startRow, this.startColumn, 0, 0));\n\n const minTimeMatrix = Array.from(new Array(this.rows), () => new Array(this.columns).fill(Number.MAX_SAFE_INTEGER));\n minTimeMatrix[this.startRow][this.startColumn] = 0;\n\n while (!minHeapForTime.isEmpty()) {\n const current = minHeapForTime.dequeue();\n if (current.row === this.targetRow && current.column === this.targetColumn) {\n break;\n }\n\n for (let move of this.MOVES) {\n const nextRow = current.row + move[0];\n const nextColumn = current.column + move[1];\n if (!isInMatrix(nextRow, nextColumn)) {\n continue;\n }\n\n const timeToMoveToNextPoint = getNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints);\n const nextValueForTime = Math.max(timeToMoveToNextPoint + current.timeFromStart,\n timeToMoveToNextPoint + moveTime[nextRow][nextColumn]);\n\n if (minTimeMatrix[nextRow][nextColumn] > nextValueForTime) {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime;\n minHeapForTime.enqueue(new Step(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime));\n }\n }\n }\n\n return minTimeMatrix[this.targetRow][this.targetColumn];\n}\n\n/**\n * @param {number} row\n * @param {number} column\n * @return {boolean}\n */\nfunction isInMatrix(row, column) {\n return row >= 0 && row < this.rows && column >= 0 && column < this.columns;\n}\n\n/**\n * @param {number} prviousTimeToMoveBetweenTwoPoints\n * @return {number}\n */\nfunction getNewTimeToMoveBetweenTwoPoints(prviousTimeToMoveBetweenTwoPoints) {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2);\n}\n```\n```TypeScript []\nfunction minTimeToReach(moveTime: number[][]): number {\n const UP = [-1, 0];\n const DOWN = [1, 0];\n const LEFT = [0, -1];\n const RIGHT = [0, 1];\n\n this.MOVES = [UP, DOWN, LEFT, RIGHT];\n\n this.rows = moveTime.length;\n this.columns = moveTime[0].length;\n\n this.startRow = 0;\n this.startColumn = 0;\n\n this.targetRow = this.rows - 1;\n this.targetColumn = this.columns - 1;\n\n return dijkstraSearchForPathWithMinTime(moveTime);\n};\n\nclass Step {\n\n row: number;\n column: number;\n timeToMoveBetweenTwoPoints: number;\n timeFromStart: number;\n\n constructor(row, column, timeToMoveBetweenTwoPoints, timeFromStart) {\n this.row = row;\n this.column = column;\n this.timeToMoveBetweenTwoPoints = timeToMoveBetweenTwoPoints;\n this.timeFromStart = timeFromStart;\n }\n}\n\nfunction dijkstraSearchForPathWithMinTime(moveTime: number[][]): number {\n const minHeapForTime = new MinPriorityQueue({ compare: (x, y) => x.timeFromStart - y.timeFromStart });\n minHeapForTime.enqueue(new Step(this.startRow, this.startColumn, 0, 0));\n\n const minTimeMatrix: number[][] = Array.from(new Array(this.rows), () => new Array(this.columns).fill(Number.MAX_SAFE_INTEGER));\n minTimeMatrix[this.startRow][this.startColumn] = 0;\n\n while (!minHeapForTime.isEmpty()) {\n const current = minHeapForTime.dequeue();\n if (current.row === this.targetRow && current.column === this.targetColumn) {\n break;\n }\n\n for (let move of this.MOVES) {\n const nextRow = current.row + move[0];\n const nextColumn = current.column + move[1];\n if (!isInMatrix(nextRow, nextColumn)) {\n continue;\n }\n\n const timeToMoveToNextPoint = getNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints);\n const nextValueForTime = Math.max(timeToMoveToNextPoint + current.timeFromStart,\n timeToMoveToNextPoint + moveTime[nextRow][nextColumn]);\n\n if (minTimeMatrix[nextRow][nextColumn] > nextValueForTime) {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime;\n minHeapForTime.enqueue(new Step(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime));\n }\n }\n }\n\n return minTimeMatrix[this.targetRow][this.targetColumn];\n}\n\nfunction isInMatrix(row: number, column: number): boolean {\n return row >= 0 && row < this.rows && column >= 0 && column < this.columns;\n}\n\nfunction getNewTimeToMoveBetweenTwoPoints(prviousTimeToMoveBetweenTwoPoints: number): number {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2);\n}\n```\n```C++ []\n#include <span>\n#include <limits>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\n\n struct Step {\n size_t row{};\n size_t column{};\n int timeToMoveBetweenTwoPoints{};\n int timeFromStart{};\n\n Step(size_t row, size_t column, int timeToMoveBetweenTwoPoints, int timeFromStart) :\n row{ row }, column{ column }, timeToMoveBetweenTwoPoints{ timeToMoveBetweenTwoPoints }, timeFromStart{ timeFromStart } {\n };\n };\n\n struct ComparatorStep {\n bool operator()(const Step& first, const Step& second) const {\n return first.timeFromStart > second.timeFromStart;\n }\n };\n\n static constexpr array<int, 2> UP = { -1, 0 };\n static constexpr array<int, 2> DOWN = { 1, 0 };\n static constexpr array<int, 2> LEFT = { 0, -1 };\n static constexpr array<int, 2> RIGHT = { 0, 1 };\n static constexpr array< array<int, 2>, 4> MOVES = { UP, DOWN, LEFT, RIGHT };\n\n size_t rows{};\n size_t columns{};\n\n size_t startRow{};\n size_t startColumn{};\n\n size_t targetRow{};\n size_t targetColumn{};\n\npublic:\n int minTimeToReach(const vector<vector<int>>& moveTime) {\n rows = moveTime.size();\n columns = moveTime[0].size();\n\n startRow = 0;\n startColumn = 0;\n\n targetRow = rows - 1;\n targetColumn = columns - 1;\n\n return dijkstraSearchForPathWithMinTime(moveTime);\n }\n\nprivate:\n int dijkstraSearchForPathWithMinTime(span<const vector<int>> moveTime) const {\n priority_queue<Step, vector<Step>, ComparatorStep> minHeapForTime;\n minHeapForTime.emplace(startRow, startColumn, 0, 0);\n\n vector<vector<int>> minTimeMatrix(rows, vector<int>(columns, numeric_limits<int>::max()));\n minTimeMatrix[startRow][startColumn] = 0;\n\n while (!minHeapForTime.empty()) {\n Step current = minHeapForTime.top();\n minHeapForTime.pop();\n if (current.row == targetRow && current.column == targetColumn) {\n break;\n }\n\n for (const auto& move : MOVES) {\n size_t nextRow = current.row + move[0];\n size_t nextColumn = current.column + move[1];\n if (!isInMatrix(nextRow, nextColumn)) {\n continue;\n }\n\n int timeToMoveToNextPoint = getNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints);\n int nextValueForTime = max(timeToMoveToNextPoint + current.timeFromStart,\n timeToMoveToNextPoint + moveTime[nextRow][nextColumn]);\n\n if (minTimeMatrix[nextRow][nextColumn] > nextValueForTime) {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime;\n minHeapForTime.emplace(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime);\n }\n }\n }\n\n return minTimeMatrix[targetRow][targetColumn];\n }\n\n bool isInMatrix(size_t row, size_t column) const {\n return row < rows && column < columns;\n }\n\n int getNewTimeToMoveBetweenTwoPoints(int prviousTimeToMoveBetweenTwoPoints) const {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2);\n }\n};\n```\n```C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution\n{\n private record Step(int row, int column, int timeToMoveBetweenTwoPoints, int timeFromStart) { }\n\n private static readonly int[] UP = { -1, 0 };\n private static readonly int[] DOWN = { 1, 0 };\n private static readonly int[] LEFT = { 0, -1 };\n private static readonly int[] RIGHT = { 0, 1 };\n private static readonly int[][] MOVES = { UP, DOWN, LEFT, RIGHT };\n\n private int rows;\n private int columns;\n\n private int startRow;\n private int startColumn;\n\n private int targetRow;\n private int targetColumn;\n\n public int MinTimeToReach(int[][] moveTime)\n {\n rows = moveTime.Length;\n columns = moveTime[0].Length;\n\n startRow = 0;\n startColumn = 0;\n\n targetRow = rows - 1;\n targetColumn = columns - 1;\n\n return DijkstraSearchForPathWithMinTime(moveTime);\n }\n\n private int DijkstraSearchForPathWithMinTime(int[][] moveTime)\n {\n PriorityQueue<Step, int> minHeapForTime = new PriorityQueue<Step, int>(\n Comparer<int>.Create((x, y) => x - y));\n\n minHeapForTime.Enqueue(new Step(startRow, startColumn, 0, 0), 0);\n\n int[][] minTimeMatrix = new int[rows][];\n for (int row = 0; row < rows; ++row)\n {\n minTimeMatrix[row] = new int[columns];\n Array.Fill(minTimeMatrix[row], int.MaxValue);\n }\n minTimeMatrix[startRow][startColumn] = 0;\n\n while (minHeapForTime.Count > 0)\n {\n Step current = minHeapForTime.Dequeue();\n if (current.row == targetRow && current.column == targetColumn)\n {\n break;\n }\n\n foreach (int[] move in MOVES)\n {\n int nextRow = current.row + move[0];\n int nextColumn = current.column + move[1];\n if (!IsInMatrix(nextRow, nextColumn))\n {\n continue;\n }\n\n int timeToMoveToNextPoint = GetNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints);\n int nextValueForTime = Math.Max(timeToMoveToNextPoint + current.timeFromStart,\n timeToMoveToNextPoint + moveTime[nextRow][nextColumn]);\n\n if (minTimeMatrix[nextRow][nextColumn] > nextValueForTime)\n {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime;\n minHeapForTime.Enqueue(new Step(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime), nextValueForTime);\n }\n }\n }\n\n return minTimeMatrix[targetRow][targetColumn];\n }\n\n private bool IsInMatrix(int row, int column)\n {\n return row >= 0 && row < rows && column >= 0 && column < columns;\n }\n\n private int GetNewTimeToMoveBetweenTwoPoints(int prviousTimeToMoveBetweenTwoPoints)\n {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2);\n }\n}\n```\n```Kotlin []\nimport java.util.PriorityQueue\nimport kotlin.math.max\n\nclass Solution {\n\n private data class Step(\n val row: Int,\n val column: Int,\n val timeToMoveBetweenTwoPoints: Int,\n val timeFromStart: Int\n ) {}\n\n private companion object {\n val UP = intArrayOf(-1, 0)\n val DOWN = intArrayOf(1, 0)\n val LEFT = intArrayOf(0, -1)\n val RIGHT = intArrayOf(0, 1)\n val MOVES = arrayOf(UP, DOWN, LEFT, RIGHT)\n }\n\n private var rows = 0\n private var columns = 0\n\n private var startRow = 0\n private var startColumn = 0\n\n private var targetRow = 0\n private var targetColumn = 0\n\n fun minTimeToReach(moveTime: Array<IntArray>): Int {\n rows = moveTime.size\n columns = moveTime[0].size\n\n startRow = 0\n startColumn = 0\n\n targetRow = rows - 1\n targetColumn = columns - 1\n\n return dijkstraSearchForPathWithMinTime(moveTime)\n }\n\n private fun dijkstraSearchForPathWithMinTime(moveTime: Array<IntArray>): Int {\n val minHeapForTime = PriorityQueue<Step>() { x, y -> x.timeFromStart - y.timeFromStart }\n minHeapForTime.add(Step(startRow, startColumn, 0, 0))\n\n val minTimeMatrix = Array<IntArray>(rows) { IntArray(columns) }\n for (row in 0..<rows) {\n minTimeMatrix[row].fill(Int.MAX_VALUE, 0, columns)\n }\n minTimeMatrix[startRow][startColumn] = 0\n\n while (!minHeapForTime.isEmpty()) {\n val current = minHeapForTime.poll()\n if (current.row == targetRow && current.column == targetColumn) {\n break\n }\n\n for (move in MOVES) {\n val nextRow = current.row + move[0]\n val nextColumn = current.column + move[1]\n if (!isInMatrix(nextRow, nextColumn)) {\n continue\n }\n\n val timeToMoveToNextPoint = getNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints)\n val nextValueForTime = max(timeToMoveToNextPoint + current.timeFromStart,\n timeToMoveToNextPoint + moveTime[nextRow][nextColumn])\n\n if (minTimeMatrix[nextRow][nextColumn] > nextValueForTime) {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime\n minHeapForTime.add(Step(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime))\n }\n }\n }\n\n return minTimeMatrix[targetRow][targetColumn]\n }\n\n private fun isInMatrix(row: Int, column: Int): Boolean {\n return row in 0..<rows && column in 0..<columns\n }\n\n private fun getNewTimeToMoveBetweenTwoPoints(prviousTimeToMoveBetweenTwoPoints: Int): Int {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2)\n }\n}\n```\n```Go []\npackage main\n\nimport (\n "container/heap"\n "fmt"\n "math"\n)\n\nvar UP = [2]int{-1, 0}\nvar DOWN = [2]int{1, 0}\nvar LEFT = [2]int{0, -1}\nvar RIGHT = [2]int{0, 1}\nvar MOVES = [4][2]int{UP, DOWN, LEFT, RIGHT}\n\nvar rows int\nvar columns int\n\nvar startRow int\nvar startColumn int\n\nvar targetRow int\nvar targetColumn int\n\nfunc minTimeToReach(moveTime [][]int) int {\n rows = len(moveTime)\n columns = len(moveTime[0])\n\n startRow = 0\n startColumn = 0\n\n targetRow = rows - 1\n targetColumn = columns - 1\n\n return dijkstraSearchForPathWithMinTime(moveTime)\n}\n\nfunc dijkstraSearchForPathWithMinTime(moveTime [][]int) int {\n minHeapForTime := make(PriorityQueue, 0)\n step := NewStep(startRow, startColumn, 0, 0)\n heap.Push(&minHeapForTime, step)\n\n minTimeMatrix := make([][]int, rows)\n for row := 0; row < rows; row++ {\n minTimeMatrix[row] = make([]int, columns)\n for column := 0; column < columns; column++ {\n minTimeMatrix[row][column] = math.MaxInt\n }\n }\n minTimeMatrix[startRow][startColumn] = 0\n\n for len(minHeapForTime) > 0 {\n current := heap.Pop(&minHeapForTime).(*Step)\n if current.row == targetRow && current.column == targetColumn {\n break\n }\n\n for _, move := range MOVES {\n nextRow := current.row + move[0]\n nextColumn := current.column + move[1]\n if !isInMatrix(nextRow, nextColumn) {\n continue\n }\n\n timeToMoveToNextPoint := getNewTimeToMoveBetweenTwoPoints(current.timeToMoveBetweenTwoPoints)\n nextValueForTime := max(timeToMoveToNextPoint+current.timeFromStart,\n timeToMoveToNextPoint+moveTime[nextRow][nextColumn])\n\n if minTimeMatrix[nextRow][nextColumn] > nextValueForTime {\n minTimeMatrix[nextRow][nextColumn] = nextValueForTime\n step := NewStep(nextRow, nextColumn, timeToMoveToNextPoint, nextValueForTime)\n heap.Push(&minHeapForTime, step)\n }\n }\n }\n\n return minTimeMatrix[targetRow][targetColumn]\n}\n\nfunc isInMatrix(row int, column int) bool {\n return row >= 0 && row < rows && column >= 0 && column < columns\n}\n\nfunc getNewTimeToMoveBetweenTwoPoints(prviousTimeToMoveBetweenTwoPoints int) int {\n return 1 + (prviousTimeToMoveBetweenTwoPoints % 2)\n}\n\ntype Step struct {\n row int\n column int\n timeToMoveBetweenTwoPoints int\n timeFromStart int\n}\n\nfunc NewStep(row int, column int, timeToMoveBetweenTwoPoints int, timeFromStart int) *Step {\n step := &Step{\n row: row,\n column: column,\n timeToMoveBetweenTwoPoints: timeToMoveBetweenTwoPoints,\n timeFromStart: timeFromStart,\n }\n return step\n}\n\ntype PriorityQueue []*Step\n\nfunc (pq PriorityQueue) Len() int {\n return len(pq)\n}\n\nfunc (pq PriorityQueue) Less(first int, second int) bool {\n return pq[first].timeFromStart < pq[second].timeFromStart\n}\n\nfunc (pq PriorityQueue) Swap(first int, second int) {\n pq[first], pq[second] = pq[second], pq[first]\n}\n\nfunc (pq *PriorityQueue) Push(object any) {\n step := object.(*Step)\n *pq = append(*pq, step)\n}\n\nfunc (pq *PriorityQueue) Pop() any {\n step := (*pq)[len(*pq)-1]\n (*pq)[len(*pq)-1] = nil\n *pq = (*pq)[0 : len(*pq)-1]\n return step\n}\n``` | 0 | 0 | ['C++', 'Java', 'Go', 'TypeScript', 'Kotlin', 'JavaScript', 'C#'] | 0 |
find-minimum-time-to-reach-last-room-ii | Simple Java Solution | simple-java-solution-by-sakshikishore-z65e | Code\njava []\nclass Node\n{\n int a,b;\n public Node(int i,int j)\n {\n a=i;\n b=j;\n }\n}\nclass Solution {\n public int minTimeToR | sakshikishore | NORMAL | 2024-11-22T05:11:41.967828+00:00 | 2024-11-22T05:11:41.967868+00:00 | 2 | false | # Code\n```java []\nclass Node\n{\n int a,b;\n public Node(int i,int j)\n {\n a=i;\n b=j;\n }\n}\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n int visited[][]=new int[moveTime.length][moveTime[0].length];\n int f[][]=new int[moveTime.length][moveTime[0].length];\n int v[][]=new int[moveTime.length][moveTime[0].length];\n for(int i=0;i<visited.length;i++)\n {\n Arrays.fill(visited[i],-1);\n }\n\n visited[0][0]=1;\n f[0][0]=0;\n Queue<Node> q=new LinkedList<Node>();\n int arr[][]=new int[moveTime.length][moveTime[0].length];\n v[0][0]=1;\n q.add(new Node(0,0));\n while(q.size()>0)\n {\n Node node=q.poll();\n int x=node.a;\n int y=node.b;\n v[x][y]=0;\n int time=arr[x][y];\n int flag=f[x][y];\n //System.out.println(x+" "+y+" "+arr[x][y]+" "+flag);\n if(x-1>=0)\n {\n if(visited[x-1][y]==-1)\n {\n visited[x-1][y]=1;\n int tim=Math.max(moveTime[x-1][y],time);\n if(flag==0)\n {\n arr[x-1][y]=tim+1;\n f[x-1][y]=1;\n if(v[x-1][y]==0)\n {\n v[x-1][y]=1;\n \n q.add(new Node(x-1,y));\n }\n }\n else\n {\n arr[x-1][y]=tim+2;\n f[x-1][y]=0;\n if(v[x-1][y]==0)\n {\n v[x-1][y]=1;\n \n q.add(new Node(x-1,y));\n }\n \n } \n }\n else\n {\n int tim=Math.max(moveTime[x-1][y],time);\n if(flag==0)\n {\n tim=tim+1;\n }\n else\n {\n tim=tim+2;\n }\n if(arr[x-1][y]>tim)\n {\n arr[x-1][y]=tim;\n \n if(flag==1)\n {\n f[x-1][y]=0;\n if(v[x-1][y]==0)\n {\n v[x-1][y]=1;\n \n q.add(new Node(x-1,y));\n }\n }\n else\n {\n f[x-1][y]=1;\n if(v[x-1][y]==0)\n {\n v[x-1][y]=1;\n \n q.add(new Node(x-1,y));\n }\n }\n }\n }\n }\n if(y-1>=0)\n {\n if(visited[x][y-1]==-1)\n {\n visited[x][y-1]=1;\n int tim=Math.max(moveTime[x][y-1],time);\n if(flag==0)\n {\n f[x][y-1]=1;\n arr[x][y-1]=tim+1;\n if(v[x][y-1]==0)\n {\n v[x][y-1]=1;\n \n q.add(new Node(x,y-1));\n }\n }\n else\n {\n arr[x][y-1]=tim+2;\n f[x][y-1]=0;\n if(v[x][y-1]==0)\n {\n v[x][y-1]=1;\n q.add(new Node(x,y-1));\n }\n } \n }\n else\n {\n int tim=Math.max(moveTime[x][y-1],time);\n if(flag==0)\n {\n tim=tim+1;\n }\n else\n {\n tim=tim+2;\n }\n if(arr[x][y-1]>tim)\n {\n \n arr[x][y-1]=tim;\n if(flag==1)\n {\n f[x][y-1]=0;\n if(v[x][y-1]==0)\n {\n v[x][y-1]=1;\n q.add(new Node(x,y-1));\n }\n }\n else\n {\n f[x][y-1]=1;\n if(v[x][y-1]==0)\n {\n v[x][y-1]=1;\n q.add(new Node(x,y-1));\n }\n }\n }\n }\n }\n if(x+1<visited.length)\n {\n if(visited[x+1][y]==-1)\n {\n visited[x+1][y]=1;\n int tim=Math.max(moveTime[x+1][y],time);\n if(flag==0)\n {\n arr[x+1][y]=tim+1;\n f[x+1][y]=1;\n if(v[x+1][y]==0)\n {\n v[x+1][y]=1;\n q.add(new Node(x+1,y));\n }\n }\n else\n {\n arr[x+1][y]=tim+2;\n f[x+1][y]=0;\n if(v[x+1][y]==0)\n {\n v[x+1][y]=1;\n q.add(new Node(x+1,y));\n }\n } \n }\n else\n {\n int tim=Math.max(moveTime[x+1][y],time);\n if(flag==0)\n {\n tim=tim+1;\n }\n else\n {\n tim=tim+2;\n }\n if(arr[x+1][y]>tim)\n {\n \n arr[x+1][y]=tim;\n if(flag==1)\n {\n f[x+1][y]=0;\n if(v[x+1][y]==0)\n {\n v[x+1][y]=1;\n q.add(new Node(x+1,y));\n }\n }\n else\n {\n f[x+1][y]=1;\n if(v[x+1][y]==0)\n {\n v[x+1][y]=1;\n q.add(new Node(x+1,y));\n }\n }\n }\n }\n }\n if(y+1<visited[0].length)\n {\n if(visited[x][y+1]==-1)\n {\n visited[x][y+1]=1;\n int tim=Math.max(moveTime[x][y+1],time);\n if(flag==0)\n {\n arr[x][y+1]=tim+1;\n f[x][y+1]=1;\n if(v[x][y+1]==0)\n {\n v[x][y+1]=1;\n q.add(new Node(x,y+1));\n }\n }\n else\n {\n arr[x][y+1]=tim+2;\n f[x][y+1]=0;\n if(v[x][y+1]==0)\n {\n v[x][y+1]=1;\n q.add(new Node(x,y+1));\n }\n\n \n } \n }\n else\n {\n int tim=Math.max(moveTime[x][y+1],time);\n if(flag==0)\n {\n tim=tim+1;\n }\n else\n {\n tim=tim+2;\n }\n if(arr[x][y+1]>tim)\n {\n \n arr[x][y+1]=tim;\n if(flag==1)\n {\n f[x][y+1]=0;\n if(v[x][y+1]==0)\n {\n v[x][y+1]=1;\n q.add(new Node(x,y+1));\n }\n }\n else\n {\n f[x][y+1]=1;\n if(v[x][y+1]==0)\n {\n v[x][y+1]=1;\n q.add(new Node(x,y+1));\n }\n }\n }\n }\n }\n }\n \n \n return arr[visited.length-1][visited[0].length-1];\n\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Java : Two Queue Dijkstra Solution | java-two-queue-dijkstra-solution-by-anur-w7eb | I use two different queues for different cases.\nWhen I am processing node, with distance 1, I add it to the QueueTwo.\nWhen I am process node with distance 2, | anuraganand789 | NORMAL | 2024-11-21T13:44:03.374007+00:00 | 2024-11-21T13:44:03.374039+00:00 | 2 | false | I use two different queues for different cases.\nWhen I am processing node, with distance 1, I add it to the QueueTwo.\nWhen I am process node with distance 2, I add it to the QueueOne.\n\n# Code\n```java []\nclass Solution {\n public int minTimeToReach(int[][] moveTime) {\n final int rowCount = moveTime.length;\n final int columnCount = moveTime[0].length;\n\n class ShortestPath {\n final int[][] directionOffset = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};\n final int[][] shortestTimeMatrix = new int[rowCount][columnCount];\n\n int calculate(){\n for(final int[] row : shortestTimeMatrix) Arrays.fill(row, Integer.MAX_VALUE);\n\n final Queue<List<Integer>> timeQueueOne = new ArrayDeque<>();\n timeQueueOne.offer(List.of(0, 0));\n shortestTimeMatrix[0][0] = 0;\n\n final Queue<List<Integer>> timeQueueTwo = new ArrayDeque<>();\n int sequence = 0;\n\n while(!timeQueueOne.isEmpty() || !timeQueueTwo.isEmpty()) {\n processQueue(timeQueueOne, timeQueueTwo, 1);\n processQueue(timeQueueTwo, timeQueueOne, 2);\n }\n\n return shortestTimeMatrix[rowCount - 1][columnCount - 1];\n }\n\n void processQueue(\n final Queue<List<Integer>> sourceTimeQueue\n , final Queue<List<Integer>> destinationTimeQueue\n , final int addAmount\n ){\n while(!sourceTimeQueue.isEmpty()) {\n final List<Integer> cellCoordinate = sourceTimeQueue.poll();\n\n final int rowIndex = cellCoordinate.get(0);\n final int columnIndex = cellCoordinate.get(1);\n final int timeCostTillNow = shortestTimeMatrix[rowIndex][columnIndex];\n\n for(final int[] direction : directionOffset){\n final int rowOffset = direction[0];\n final int columnOffset = direction[1];\n\n final int nextRowIndex = rowIndex + rowOffset;\n if(nextRowIndex < 0 || nextRowIndex >= rowCount) continue;\n\n final int nextColumnIndex = columnIndex + columnOffset;\n if(nextColumnIndex < 0 || nextColumnIndex >= columnCount) continue;\n\n final int minimumTimeToMove = moveTime[nextRowIndex][nextColumnIndex];\n int updatedTimeTillNow = (timeCostTillNow > minimumTimeToMove) ? timeCostTillNow : minimumTimeToMove;\n\n final int shortestTimeCell = shortestTimeMatrix[nextRowIndex][nextColumnIndex];\n\n if(shortestTimeCell > (updatedTimeTillNow + addAmount)) {\n final int shortestTimeNow = updatedTimeTillNow + addAmount;\n shortestTimeMatrix[nextRowIndex][nextColumnIndex] = shortestTimeNow;\n destinationTimeQueue.offer(List.of(nextRowIndex, nextColumnIndex));\n }\n }\n }\n }\n }\n\n final ShortestPath shortestTime = new ShortestPath();\n final int shortestTimeToLastRoom = shortestTime.calculate();\n\n return shortestTimeToLastRoom;\n }\n}\n``` | 0 | 0 | ['Shortest Path', 'Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | [C++] Dijkstra's Algorithm | c-dijkstras-algorithm-by-enniggma-sgwn | Code\ncpp []\nclass Solution {\npublic:\n int dx[4] = {-1, 1, 0, 0};\n int dy[4] = {0, 0, -1, 1};\n const long long INF = 1e15;\n int minTimeToReach | AwakenX | NORMAL | 2024-11-14T18:07:10.246680+00:00 | 2024-11-14T18:07:10.246723+00:00 | 3 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int dx[4] = {-1, 1, 0, 0};\n int dy[4] = {0, 0, -1, 1};\n const long long INF = 1e15;\n int minTimeToReach(vector<vector<int>>& arr) {\n int n = arr.size();\n int m = arr[0].size();\n priority_queue<pair<int, pair<pair<int, int>, int>>, vector<pair<int, pair<pair<int, int>, int>>>, greater<pair<int, pair<pair<int, int>, int>>>> pq;\n vector<vector<long long>> distance(n, vector<long long>(m, INF));\n pq.push({0, {{0, 0}, 1}});\n distance[0][0] = 0;\n while(!pq.empty()) {\n auto z = pq.top();\n int x = z.second.first.first;\n int y = z.second.first.second;\n int cost = z.first;\n int turn = z.second.second;\n if(x == n - 1 && y == m - 1) {\n return cost;\n }\n pq.pop();\n for(int j = 0; j < 4; j++) {\n int newX = x + dx[j];\n int newY = y + dy[j];\n if(newX >= 0 && newY >= 0 && newX < n && newY < m) {\n \n int newDistance = cost + turn;\n if(arr[newX][newY] >= cost) {\n newDistance = cost + arr[newX][newY] - cost + turn;\n }\n \n if(distance[newX][newY] > newDistance) {\n distance[newX][newY] = newDistance;\n int newTurn = turn == 1 ? 2 : 1;\n pq.push({newDistance, {{newX, newY}, newTurn}});\n }\n }\n } \n }\n // Will not reach here\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra's algo | dijkstras-algo-by-up41guy-6jpm | javascript []\nclass MinMaxPriorityQueue {\n\n #heap = []\n #compare;\n\n constructor(compare) {\n this.#heap = [];\n this.#compare = compare || ((a, b | Cx1z0 | NORMAL | 2024-11-13T15:00:33.843868+00:00 | 2024-11-13T15:00:33.843903+00:00 | 3 | false | ```javascript []\nclass MinMaxPriorityQueue {\n\n #heap = []\n #compare;\n\n constructor(compare) {\n this.#heap = [];\n this.#compare = compare || ((a, b) => a - b) //By default, keep it MinHeap\n }\n\n // Add a new element to the priority queue\n enqueue = (value) => {\n this.#heap.push(value);\n this.#heapifyUp(this.#heap.length - 1);\n }\n\n // Remove and return the element with the highest priority (smallest for min-heap, largest for max-heap)\n dequeue = () => {\n if (this.#heap.length === 0) return null;\n const root = this.#heap[0];\n const end = this.#heap.pop();\n if (this.#heap.length > 0) {\n this.#heap[0] = end;\n this.#heapifyDown(0);\n }\n return root;\n }\n\n // Peek at the element with the highest priority without removing it\n peek = () => {\n return this.#heap.length > 0 ? this.#heap[0] : null;\n }\n\n // Check if the priority queue is empty\n isEmpty = () => {\n return this.#heap.length === 0;\n }\n\n // Get the size of the priority queue\n size = () => {\n return this.#heap.length;\n }\n\n // Get the heap\n get heap() {\n return this.#heap\n }\n\n // Maintain heap property by moving element up\n #heapifyUp = (index) => {\n let parent = Math.floor((index - 1) / 2);\n while (index > 0 && this.#compare(this.#heap[index], this.#heap[parent]) < 0) {\n this.#swap(index, parent)\n index = parent;\n parent = Math.floor((index - 1) / 2);\n }\n }\n\n // Maintain heap property by moving element down\n #heapifyDown = (index) => {\n const length = this.#heap.length;\n let left = 2 * index + 1;\n let right = 2 * index + 2;\n let extreme = index;\n\n if (left < length && this.#compare(this.#heap[left], this.#heap[extreme]) < 0) {\n extreme = left;\n }\n\n if (right < length && this.#compare(this.#heap[right], this.#heap[extreme]) < 0) {\n extreme = right;\n }\n\n if (extreme !== index) {\n this.#swap(index, extreme)\n this.#heapifyDown(extreme);\n }\n }\n\n #swap = (i, j) => {\n [this.#heap[i], this.#heap[j]] = [this.#heap[j], this.#heap[i]]\n }\n}\n\n/**\n * @param {number[][]} moveTime\n * @return {number}\n */\nfunction minTimeToReach(moveTime) {\n const n = moveTime.length;\n const m = moveTime[0].length;\n\n const pq = new MinMaxPriorityQueue((a, b) => a[0] - b[0]);\n const dist = Array.from({ length: n }, () => Array(m).fill(Infinity));\n\n pq.enqueue([0, 0, 0, 1]); // [time, row, col, turn]\n dist[0][0] = 0;\n\n const directions = [\n [-1, 0], // up\n [0, 1], // right\n [1, 0], // down\n [0, -1] // left\n ];\n\n while (!pq.isEmpty()) {\n const [time, row, col, turn] = pq.dequeue();\n\n if (row === n - 1 && col === m - 1) {\n return time;\n }\n\n for (const [drow, dcol] of directions) {\n const nrow = row + drow;\n const ncol = col + dcol;\n\n if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m) {\n const maxtime = Math.max(time, moveTime[nrow][ncol]) + (turn === 1 ? 1 : 2);\n\n if (dist[nrow][ncol] > maxtime) {\n dist[nrow][ncol] = maxtime;\n pq.enqueue([maxtime, nrow, ncol, 1 - turn]);\n }\n }\n }\n }\n return -1;\n}\n``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'JavaScript'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra's algo | dijkstras-algo-by-up41guy-1rno | javascript []\nclass MinMaxPriorityQueue {\n\n #heap = []\n #compare;\n\n constructor(compare) {\n this.#heap = [];\n this.#compare = compare || ((a, b | Cx1z0 | NORMAL | 2024-11-13T14:59:55.006387+00:00 | 2024-11-13T14:59:55.006423+00:00 | 0 | false | ```javascript []\nclass MinMaxPriorityQueue {\n\n #heap = []\n #compare;\n\n constructor(compare) {\n this.#heap = [];\n this.#compare = compare || ((a, b) => a - b) //By default, keep it MinHeap\n }\n\n // Add a new element to the priority queue\n enqueue = (value) => {\n this.#heap.push(value);\n this.#heapifyUp(this.#heap.length - 1);\n }\n\n // Remove and return the element with the highest priority (smallest for min-heap, largest for max-heap)\n dequeue = () => {\n if (this.#heap.length === 0) return null;\n const root = this.#heap[0];\n const end = this.#heap.pop();\n if (this.#heap.length > 0) {\n this.#heap[0] = end;\n this.#heapifyDown(0);\n }\n return root;\n }\n\n // Peek at the element with the highest priority without removing it\n peek = () => {\n return this.#heap.length > 0 ? this.#heap[0] : null;\n }\n\n // Check if the priority queue is empty\n isEmpty = () => {\n return this.#heap.length === 0;\n }\n\n // Get the size of the priority queue\n size = () => {\n return this.#heap.length;\n }\n\n // Get the heap\n get heap() {\n return this.#heap\n }\n\n // Maintain heap property by moving element up\n #heapifyUp = (index) => {\n let parent = Math.floor((index - 1) / 2);\n while (index > 0 && this.#compare(this.#heap[index], this.#heap[parent]) < 0) {\n this.#swap(index, parent)\n index = parent;\n parent = Math.floor((index - 1) / 2);\n }\n }\n\n // Maintain heap property by moving element down\n #heapifyDown = (index) => {\n const length = this.#heap.length;\n let left = 2 * index + 1;\n let right = 2 * index + 2;\n let extreme = index;\n\n if (left < length && this.#compare(this.#heap[left], this.#heap[extreme]) < 0) {\n extreme = left;\n }\n\n if (right < length && this.#compare(this.#heap[right], this.#heap[extreme]) < 0) {\n extreme = right;\n }\n\n if (extreme !== index) {\n this.#swap(index, extreme)\n this.#heapifyDown(extreme);\n }\n }\n\n #swap = (i, j) => {\n [this.#heap[i], this.#heap[j]] = [this.#heap[j], this.#heap[i]]\n }\n}\n\n/**\n * @param {number[][]} moveTime\n * @return {number}\n */\nfunction minTimeToReach(moveTime) {\n const n = moveTime.length;\n const m = moveTime[0].length;\n\n const pq = new MinMaxPriorityQueue((a, b) => a[0] - b[0]);\n const dist = Array.from({ length: n }, () => Array(m).fill(Infinity));\n\n pq.enqueue([0, 0, 0, 1]); // [time, row, col, turn]\n dist[0][0] = 0;\n\n const directions = [\n [-1, 0], // up\n [0, 1], // right\n [1, 0], // down\n [0, -1] // left\n ];\n\n while (!pq.isEmpty()) {\n const [time, row, col, turn] = pq.dequeue();\n\n if (row === n - 1 && col === m - 1) {\n return time;\n }\n\n for (const [drow, dcol] of directions) {\n const nrow = row + drow;\n const ncol = col + dcol;\n\n if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m) {\n const maxtime = Math.max(time, moveTime[nrow][ncol]) + (turn === 1 ? 1 : 2);\n\n if (dist[nrow][ncol] > maxtime) {\n dist[nrow][ncol] = maxtime;\n pq.enqueue([maxtime, nrow, ncol, 1 - turn]);\n }\n }\n }\n }\n return -1;\n}\n``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'JavaScript'] | 0 |
find-minimum-time-to-reach-last-room-ii | Heap/PriorityQueue || Java || Dijkstra || Clean code | heappriorityqueue-java-dijkstra-clean-co-fvjv | 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 | owaispatel95 | NORMAL | 2024-11-13T07:33:54.900153+00:00 | 2024-11-13T07:33:54.900177+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public static int max = (int) (1e9);\n public static final int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n\n public static class Pair {\n public int r, c, ele, offset;\n\n public Pair(\n final int r,\n final int c,\n final int ele,\n final int offset) {\n this.r = r;\n this.c = c;\n this.ele = ele;\n this.offset = offset;\n }\n }\n\n public int minTimeToReach(int[][] moveTime) {\n final int n = moveTime.length;\n final int m = moveTime[0].length;\n final int[][] weights = new int[n][m];\n final PriorityQueue<Pair> queue = new PriorityQueue<>((a, b) -> a.ele - b.ele);\n\n for (int i = 0; i < n; i++) Arrays.fill(weights[i], max);\n\n weights[0][0] = moveTime[0][0] = 0;\n queue.add(new Pair(0, 0, moveTime[0][0], 2));\n\n while(!queue.isEmpty()) {\n final Pair curPair = queue.remove();\n\n if (curPair.r == n - 1 && curPair.c == m - 1) return weights[n - 1][m - 1];\n\n for (final int[] move : moves) { \n final int childR = curPair.r + move[0]; \n final int childC = curPair.c + move[1];\n final int curOffset = (curPair.offset == 2 ? 1 : 2);\n\n if (childR < 0 \n || childR >= n\n || childC < 0 \n || childC >= m) continue;\n\n if (weights[childR][childC] == max \n || weights[childR][childC] > weights[curPair.r][curPair.c] + 1) {\n weights[childR][childC] = Integer.max(moveTime[childR][childC], weights[curPair.r][curPair.c]) + curOffset;\n\n queue.add(new Pair(childR, childC, weights[childR][childC], curOffset));\n }\n }\n }\n\n // Arrays.stream(weights).forEach(x -> System.out.println(Arrays.toString(x)));\n\n return -1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Easy BFS ✅ | easy-bfs-by-vedantagrawal524-cytc | Code\ncpp []\nclass Solution {\npublic:\n int dr[4]={-1,1,0,0};\n int dc[4]={0,0,-1,1};\n int bfs(vector<vector<int>>& moveTime,int n,int m,vector<vect | vedantagrawal524 | NORMAL | 2024-11-12T10:42:47.110166+00:00 | 2024-11-12T10:42:47.110200+00:00 | 5 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int dr[4]={-1,1,0,0};\n int dc[4]={0,0,-1,1};\n int bfs(vector<vector<int>>& moveTime,int n,int m,vector<vector<int>>& time){\n priority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>>q;\n q.push({0,0,0,0});\n time[0][0]=0;\n while(!q.empty()){\n auto tp=q.top();\n q.pop();\n int timer=tp[0];\n int move=tp[1];\n int r=tp[2];\n int c=tp[3];\n for(int i=0;i<4;i++){\n int nr=r+dr[i];\n int nc=c+dc[i];\n if(nr>=0 && nr<n && nc>=0 && nc<m){\n int maxTime=max(timer,moveTime[nr][nc])+move+1;\n if(maxTime<time[nr][nc]){\n if(nr==n-1 && nc==m-1) return maxTime;\n time[nr][nc]=maxTime;\n q.push({maxTime,1-move,nr,nc});\n }\n }\n }\n }\n return time[n-1][m-1];\n }\n int minTimeToReach(vector<vector<int>>& moveTime){\n int n=moveTime.size();\n int m=moveTime[0].size();\n vector<vector<int>>time(n,vector<int>(m,INT_MAX));\n return bfs(moveTime,n,m,time);\n }\n};\n``` | 0 | 0 | ['Array', 'Breadth-First Search', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Simple Solution beats 100% using priority queue | simple-solution-beats-100-using-priority-8ka8 | 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 | vikash_kumar_dsa2 | NORMAL | 2024-11-12T07:45:45.403258+00:00 | 2024-11-12T07:45:45.403302+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n priority_queue<pair<pair<int, int>, pair<int, int>>, vector<pair<pair<int, int>, pair<int, int>>>, greater<pair<pair<int, int>, pair<int, int>>>> pq;\n pq.push({{0,1},{0,0}});\n int m = moveTime.size();\n int n = moveTime[0].size();\n vector<vector<int>> vis(m,vector<int>(n,INT_MAX));\n int dx[4] = {-1,0,1,0};\n int dy[4] = {0,1,0,-1};\n vis[0][0] = 0;\n while(!pq.empty()){\n auto tp = pq.top();\n int time = tp.first.first;\n int alt = tp.first.second;\n int x = tp.second.first;\n int y = tp.second.second;\n if(x == m-1 && y == n-1){\n return time;\n }\n pq.pop();\n for(int i = 0;i<4;i++){\n int nx = x + dx[i];\n int ny = y + dy[i];\n if(nx >= 0 && nx < m && ny >= 0 && ny < n){\n int nextTime;\n if(alt){\n nextTime = max(time,moveTime[nx][ny])+1;\n if(nextTime < vis[nx][ny]){\n vis[nx][ny] = nextTime;\n pq.push({{nextTime,0},{nx,ny}});\n }\n }else{\n nextTime = max(time,moveTime[nx][ny])+2;\n if(nextTime < vis[nx][ny]){\n vis[nx][ny] = nextTime;\n pq.push({{nextTime,1},{nx,ny}});\n }\n }\n \n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Array', 'Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | using priority queue | using-priority-queue-by-aartik001-2jlg | 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 | aartik001 | NORMAL | 2024-11-11T21:00:02.146887+00:00 | 2024-11-11T21:00:02.146926+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n\nclass Solution {\npublic:\n \n \n int minTimeToReach(vector<vector<int>>& mt) {\n int n=mt.size();\n int m=mt[0].size();\n\n \nint rr[4]={1,-1,0,0};\nint cc[4]={0,0,-1,1};\n priority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>>pq;\n\n vector<vector<int>>vis(n,vector<int>(m,0));\n\n pq.push({0,1,0,0});\n vis[0][0]=1;\n\n while(!pq.empty()){\n auto it=pq.top();\n pq.pop();\n\n int time=it[0];\n int stp=it[1];\n \n int x=it[2];\n int y=it[3];\n if(x==n-1&&y==m-1){\n return time;\n }\n for(int k=0;k<4;k++){\n int newr=rr[k]+x;\n int newc=cc[k]+y;\n if(newr>=0&&newr<n&&newc>=0&&newc<m&&vis[newr][newc]==0){\n int newtime=max(time,mt[newr][newc])+stp;\n\n int newstp=2;\n if(stp==2){\n newstp=1;\n }\n \n\n\n pq.push({newtime,newstp,newr,newc});\n vis[newr][newc]=1;\n }\n }\n }\n return 0;\n }\n};\n\n``` | 0 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | [scala] - Dijkstra, immutable, recursion | scala-dijkstra-immutable-recursion-by-ni-xq9s | I am deeply concerned by the amount of attention given to Scala. Please upvote and submit your solutions.\n\n# Code\nscala []\nobject Solution {\n import scala | nikiforo | NORMAL | 2024-11-09T19:58:19.097884+00:00 | 2024-11-09T19:58:19.097912+00:00 | 4 | false | I am deeply concerned by the amount of attention given to Scala. Please upvote and submit your solutions.\n\n# Code\n```scala []\nobject Solution {\n import scala.collection.immutable.TreeSet\n\n def minTimeToReach(moveTime: Array[Array[Int]]): Int = {\n def inBorder(c: (Int, Int)) = c._1 >= 0 && c._1 < moveTime.length && c._2 >= 0 && c._2 < moveTime.head.length\n def go(visited: Set[(Int, Int)], toVisit: TreeSet[(Int, Int, Int, Boolean)]): Int = {\n val (cost, i, j, one) = toVisit.head\n if (i == moveTime.length - 1 && j == moveTime.head.length - 1) cost\n else {\n val neighbours = neighbour4(i, j).filter(inBorder).filter(!visited.contains(_))\n val next = neighbours.map(c => (math.max(cost, moveTime(c._1)(c._2)) + (if(one) 1 else 2), c._1, c._2, !one))\n go(visited + ((i, j)), toVisit.tail ++ next)\n }\n }\n\n go(Set((0, 0)), TreeSet((0, 0, 0, true)))\n }\n\n private def neighbour4(i: Int, j: Int): List[(Int, Int)] = List((i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1))\n}\n``` | 0 | 0 | ['Scala'] | 0 |
find-minimum-time-to-reach-last-room-ii | modified Dijkstra (strivers solution is modifed) | modified-dijkstra-strivers-solution-is-m-ku6e | 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 | sangdilcompetes | NORMAL | 2024-11-09T17:02:32.873615+00:00 | 2024-11-09T17:02:32.873642+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n\n int n = moveTime.size();\n int m = moveTime[0].size();\n priority_queue<pair<int, pair<int, pair<int, bool>>>, \n vector<pair<int, pair<int, pair<int, bool>>>>, \n greater<pair<int, pair<int, pair<int, bool>>>>> pq;\n vector<vector<int>> dist(n, vector<int>(m, INT_MAX));\n\n pq.push({0,{0,{0,false}}});\n dist[0][0] = 0;\n\n int dx[] = {0,1,0,-1}; \n int dy[] = {1,0,-1,0};\n\n while(!pq.empty()){\n auto X = pq.top();\n pq.pop();\n int distance = X.first;\n int i = X.second.first;\n int j = X.second.second.first;\n bool flg = X.second.second.second;\n\n for( int d = 0 ; d<4 ; d++){\n int newi = i + dx[d];\n int newj = j + dy[d];\n\n if(newi >= 0 && newi < n && newj >= 0 && newj < m){\n int temp = max(distance, moveTime[newi][newj]);\n if(flg)temp++;\n temp++;\n if(temp < dist[newi][newj]){\n dist[newi][newj] = temp;\n pq.push({temp, {newi,{ newj, !flg}}});\n }\n }\n }\n }\n\n return dist[n-1][m-1];\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | C++ 250 ms | c-250-ms-by-eridanoy-k1a3 | 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 | eridanoy | NORMAL | 2024-11-09T17:02:07.831724+00:00 | 2024-11-09T17:02:07.831756+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n struct Room {\n int row = 0;\n int col = 0;\n int time = 0;\n bool first = false;\n bool operator==(const Room& rhs) const {\n return row == rhs.row and col == rhs.col;\n }\n bool operator<(const Room& rhs) const {\n return time > rhs.time;\n }\n };\n\n constexpr int visited = -1;\n constexpr int dd[4][2] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n const int height = size(moveTime);\n const int width = size(moveTime.front());\n const Room end = {height - 1, width - 1};\n\n auto is_valid = [&](const Room& room) {\n if(room.row < 0 or room.row >= height or\n room.col < 0 or room.col >= width) return false;\n return true;\n };\n\n priority_queue<Room> rooms;\n rooms.push({});\n moveTime[0][0] = visited;\n while(!rooms.empty()) {\n const Room curr = rooms.top();\n rooms.pop();\n if(curr == end) return curr.time;\n for(const auto& [dr, dc] : dd) {\n Room next = {curr.row + dr, curr.col + dc};\n if(is_valid(next) and moveTime[next.row][next.col] != visited) {\n int time = moveTime[next.row][next.col];\n next.time = (curr.time < time? time: curr.time) + (curr.first? 2: 1);\n next.first = curr.first ^ 1;\n rooms.push(next);\n moveTime[next.row][next.col] = visited;\n }\n }\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra Alg Easy | dijkstra-alg-easy-by-gps_357-zuyo | 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 | gps_357 | NORMAL | 2024-11-08T13:57:29.186826+00:00 | 2024-11-08T13:57:29.186857+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n vector<vector<int>> vi;\n vector<vector<int>> dt;\n int dx[4] = {0,0,1,-1};\n int dy[4] = {-1,1,0,0};\n int n,m;\n bool isvalid(int x,int y){\n return (x>=0 and y>=0 and x<n and y<m);\n }\ntypedef pair<int,pair<int,pair<int,int>>> p;\n int minTimeToReach(vector<vector<int>>& mt) {\n \n n = mt.size();\n m = mt[0].size();\n \n // memset(vi,0,sizeof(vi));\n dt = mt;\n vi = mt;\n for(int i =0;i<n;i++){\n for(int j =0;j<m;j++)\n dt[i][j] = 1e9+2500, vi[i][j] = 0; \n }\n\n priority_queue<p,vector<p>,greater<p>> pq;\n\n pq.push({0,{2,{0,0}}});\n dt[0][0] = 0;\n\n while(!pq.empty()){\n\n auto a = pq.top();\n\n pq.pop();\n\n int dist = a.first;\n int prev = a.second.first;\n int x = a.second.second.first;\n int y = a.second.second.second;\n\n if(vi[x][y]) continue;\n\n vi[x][y] = 1;\n\n for(int i =0 ;i<4;i++){\n int xx = x + dx[i];\n int yy = y + dy[i];\n\n if(isvalid(xx,yy)){\n if(dt[xx][yy]> max(dt[x][y],mt[xx][yy])+2 and prev==1){\n dt[xx][yy] = max(dt[x][y],mt[xx][yy])+2 ;\n pq.push({dt[xx][yy],{2,{xx,yy}}});\n }\n\n if(dt[xx][yy]> max(dt[x][y],mt[xx][yy])+1 and prev==2){\n dt[xx][yy] = max(dt[x][y],mt[xx][yy])+1 ;\n pq.push({dt[xx][yy],{1,{xx,yy}}});\n }\n }\n }\n }\n\n return dt[n-1][m-1];\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Using Dijstra algorithm 100% faster solution | using-dijstra-algorithm-100-faster-solut-dcmh | 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 | Balram_54321 | NORMAL | 2024-11-08T10:07:51.955368+00:00 | 2024-11-08T10:07:51.955389+00:00 | 5 | 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- o(V+E)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(V)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n typedef long long ll;\n typedef pair<ll, pair<int, int>> iPair;\n vector<int> x_cord = {1, 0, -1, 0};\n vector<int> y_cord = {0, -1, 0, 1};\n\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m = moveTime.size(), n = moveTime[0].size();\n\n int src =0;\n vector<ll> dist(m*n, -1);\n\n priority_queue<iPair, vector<iPair>, greater<iPair>> pq;\n\n pq.push({0, {src, 1}});\n dist[src] = 0;\n\n while(!pq.empty()){\n iPair node = pq.top();\n int x = node.second.first/n, y = node.second.first%n; \n pq.pop();\n\n for(int i=0;i<4;i++){ \n int row = x + x_cord[i], col = y + y_cord[i];\n int nbr = row*n + col;\n\n if(row<0 || row> m-1) continue;\n if(col<0 || col> n-1) continue;\n \n if(dist[nbr]==-1){\n int next_move_time = node.second.second==1? 2:1;\n ll nbr_dist = max(node.first, (long long)moveTime[row][col])+ node.second.second;\n pq.push({nbr_dist, {nbr, next_move_time}});\n dist[nbr] = nbr_dist;\n }\n }\n }\n\n return (int)dist[m*n-1];\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra's | dijkstras-by-lambdacode-dev-gpsn | Intuition\n- No significant change to version I problem. just add move time step to the state variable.\n\n \n# Code\ncpp []\nclass Solution {\npublic:\n int | lambdacode-dev | NORMAL | 2024-11-07T22:23:22.897595+00:00 | 2024-11-07T22:23:22.897627+00:00 | 1 | false | # Intuition\n- No significant change to version I problem. just add move time step to the state variable.\n\n \n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int rows = moveTime.size(), cols = moveTime[0].size();\n using State = array<int,4>; // (t, r, c, step) : best time t to reach (r,c) so far, and next move step\n vector<vector<int>> bsf(rows, vector<int>(cols, INT_MAX)); // best so far\n priority_queue<State, vector<State>, greater<>> pq;\n pq.push({0, 0, 0, 1});\n while(!pq.empty()) {\n auto [t, r, c, step] = pq.top();\n pq.pop();\n if(r + 1 == rows && c+1 == cols)\n return t;\n bsf[r][c] = -t; // negate to mark it as done\n for(auto const& [dr, dc] : vector<array<int,2>>{ {0,1}, {0, -1}, {1, 0}, {-1,0}}) {\n if(auto R = r+dr, C = c+dc; R >= 0 && R < rows && C >= 0 && C < cols && bsf[R][C] > 0) {\n if(auto alt = std::max(t, moveTime[R][C]) + step; alt < bsf[R][C]) {\n bsf[R][C] = alt;\n pq.push({alt, R, C, 3-step});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijsktra's || C++ | dijsktras-c-by-lotus18-mkpt | Code\ncpp []\nclass Solution \n{\npublic:\n bool valid(int r, int c, int rows, int cols)\n {\n return (r>=0 && r<rows && c>=0 && c<cols);\n }\n | lotus18 | NORMAL | 2024-11-06T10:19:29.510266+00:00 | 2024-11-06T10:19:29.510296+00:00 | 2 | false | # Code\n```cpp []\nclass Solution \n{\npublic:\n bool valid(int r, int c, int rows, int cols)\n {\n return (r>=0 && r<rows && c>=0 && c<cols);\n }\n int minTimeToReach(vector<vector<int>>& moveTime) \n {\n int rows=moveTime.size(), cols=moveTime[0].size();\n priority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>> q;\n vector<vector<int>> vis(rows+1, vector<int> (cols+1,0));\n q.push({0,0,0,1});\n vis[0][0]=1;\n vector<pair<int,int>> directions={{1,0},{-1,0},{0,1},{0,-1}};\n while(!q.empty())\n {\n auto v=q.top();\n q.pop();\n int time=v[0];\n int r=v[1], c=v[2];\n int cost=v[3];\n if(r==rows-1 && c==cols-1) return time;\n for(auto it: directions)\n {\n int dr=r+it.first, dc=c+it.second;\n if(valid(dr,dc,rows,cols) && !vis[dr][dc]) \n {\n vis[dr][dc]=1;\n int newTime=max(moveTime[dr][dc]+cost,time+cost);\n q.push({newTime,dr,dc,cost==1?2:1});\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Graph', 'Heap (Priority Queue)', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkshtra's Algorithm | modified-dijkshtras-algorithm-by-siddhar-f8u2 | Intuition\nThink of standing at $currentPosition$ and you have 4 possible directions to move. If you took $cost$ time to reach to a point where you are currentl | siddharthraja9849 | NORMAL | 2024-11-06T03:52:36.269979+00:00 | 2024-11-06T03:52:36.270003+00:00 | 12 | false | # Intuition\nThink of standing at $currentPosition$ and you have 4 possible directions to move. If you took $cost$ time to reach to a point where you are currently and you can move from $currentPosition$ to the $nextPosition$ using a $nextCost$ would you move if earlier you already visited the $nextPosition$ with some cost greater than $nextCost$? Will you do it? Ask yourself? This is optimisation on top of $Dijkshtra\'s$.\n\nAlternate movement can be a state while moving from one $currentPosition$ to the $nextPosition$.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialise $costDP$ matrix of size $(n,m)$ to maintain minimum cost taken to reach a position index **{x,y}**\n2. Initialise an increasing $priorityQueue$ with states **{cost, rowIndex, columnIndex, prevMove}** with values **{0,0,0,2}**\n3. $costDP[0][0]$ would be set to 0 and $prevMove$ will be set to 2\n4. Initialise $moves$ matrix with possible four directional positions\n5. Iterate on $priorityQueue$ till either it is not empty or you reach till $(n-1,m-1)$ position of $grid$\n6. $nextMove$ while iteration needs to be alternative so check what was $prevMove$ in $priorityQueue$ and assign it accordingly\n7. check whether $nextX$ $nextY$ is valid or not if it is valid check whether you can move from $currentPosition$ to the $nextPosition$ using a $nextCost$ would you move if earlier you already visited the $nextPosition$ with some cost greater than $nextCost$ our *Intuition*.\n8. push the **nextCost, nextX, nextY, nextMove** in $priorityQueue$ and repeat step *5*\n\n\nFor alternate movement between $1$ and $2$ maintain the $previousMove$ as a state in **priorityQueue** while implementing $Dijkshtra\'s$.\n\n# Complexity\n- Time complexity: $$O(n * m * log(m*n))$$\nWhere $n$: number of rows in grid\nand $m$: number of columns in grid\n\n- Space complexity: $$O(n*m)$$\nWhere $n$: number of rows in grid\nand $m$: number of columns in grid\n\n# Code\n```cpp []\nclass Solution {\npublic:\n #define tpiii tuple<int,int,int,int>\n\n bool isValid(int R,int C, int x, int y) {\n return x>=0&&x<R&&y>=0&&y<C;\n }\n\n int minTimeToReach(vector<vector<int>>& grid) {\n priority_queue<tpiii, vector<tpiii>, greater<tpiii>>Q;\n int R = grid.size();\n int C = grid[0].size();\n\n vector<vector<int>>costDP(R,vector<int>(C,INT_MAX));\n\n Q.push({0,0,0,2});\n costDP[0][0] = 0;\n\n vector<vector<int>> moves = {\n {0,1},\n {1,0},\n {0,-1},\n {-1,0}\n };\n\n\n while(!Q.empty()) {\n auto [cost, x, y, prevMove] = Q.top();\n \n int nextMove = (prevMove==1)?2:1;\n if(x==R-1&&y==C-1) {\n return cost;\n }\n\n Q.pop();\n\n for(auto ele:moves) {\n int nextX = ele[0] + x;\n int nextY = ele[1] + y;\n if(isValid(R,C, nextX, nextY)) {\n int nextCost = max(cost, grid[nextX][nextY]) + nextMove;\n if(nextCost<costDP[nextX][nextY]) {\n costDP[nextX][nextY] = nextCost;\n Q.push({nextCost, nextX, nextY, nextMove});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra's Algorithm | dijkstras-algorithm-by-rancha124-h8v6 | \nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n import heapq\n m, n = len(moveTime), len(moveTime[0])\n | Rancha124 | NORMAL | 2024-11-06T01:38:57.419811+00:00 | 2024-11-06T01:38:57.419847+00:00 | 14 | false | ```\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n import heapq\n m, n = len(moveTime), len(moveTime[0])\n heap = []\n\t\t# state could be 0 (1 sec to reach adjacent cell) or 1 (2 sec to reach adjacent cell)\n heapq.heappush(heap, (0, 0, 0, 0)) # minTime in which I can reach a node, r, c, state\n visited = [ [0 for i in range(n)] for j in range(m) ]\n def isValid(r,c):\n nonlocal m\n nonlocal n\n if 0 <= r < m and 0 <= c < n:\n return True\n return False\n \n while heap:\n time, r, c, state = heapq.heappop(heap)\n extra = 1 if state == 0 else 2\n if visited[r][c] == 1:\n continue\n if r == m-1 and c == n-1:\n return time\n visited[r][c] = 1\n directions = [[1,0],[-1,0],[0,1],[0,-1]]\n for x,y in directions:\n nr, nc = x + r, y + c \n if isValid(nr,nc):\n heapq.heappush(heap,(extra + max(time, moveTime[nr][nc]),nr,nc, (state+1) % 2))\n``` | 0 | 0 | ['Python'] | 0 |
find-minimum-time-to-reach-last-room-ii | Modified Dijkstra with Clear Data Structure Definition | modified-dijkstra-with-clear-data-struct-d4k2 | Intuition\nBased on the fact that there may be a gap build by large enter time limit, it\'s easy to see that standard DFS/BFS mechanism may not work well, as a | xpressz | NORMAL | 2024-11-05T23:30:07.405189+00:00 | 2024-11-05T23:30:07.405233+00:00 | 10 | false | # Intuition\nBased on the fact that there may be a gap build by large enter time limit, it\'s easy to see that standard DFS/BFS mechanism may not work well, as a "detour" may be welcomed. Example:\n\n```\n[\n [0, 100, 0, 0, 0],\n [0, 0, 0, 100, 0]\n]\n```\n\nThe path would go in a strange way, with down step first and then another up step:\n```\n(0, 0) -> (0, 1) -> (1, 1) -> (1, 2) -> (0, 2) -> (0, 3) -> (0, 4) -> (1, 4)\n```\n\nIn this case, Dijkstra should be the recommended approach, as Dijkstra has the capability to select from the "smallest from the beginning" for each of the iteration, thus bypass the "large block" and achieve detour.\n\nHowever, Dijkstra\'s algorithm may need to be slightly modified, as "smallest" can come from two different sources in this variant of the question - which is either a step of 1, or a step of 2. It means it may still be worthwhile to visit a node twice, in order to reach a smaller +1 step, instead of a larger +2 step, in the next iteration. \n\n# Approach\n\nDefine `result_map` data structure to hold the current minimum value. This is similar to Dijkstra\'s algorithm\'s original concept of where a "determined value" may be placed, through constantly providing a smaller alertnative from it once a new vertex is populated from a heap and may provide a smaller distance to it.\n\nHowever, the "determined value" will have to take two value: either arrived with one step, which is `min_dist_arrive_1`, or arrived with two step, which is `min_dist_arrive_2`, and update will happen as long as one of such value can be updated to a more ideal value.\n\nTo support the population of such data structure, we need to create a heap.\n\nWe define the heap as `(min_dist, uuid, (min_dist_arrive_1, min_dist_arrive_2), (x, y))`. The `min_dist` is the key element being used to prioritized processing the smallest element, and the `uuid` is just a comparison provide to break even without the need to involve comparison within `(min_dist_arrive_1, min_dist_arrive_2)` where one of them can be `None` and is not supported by Python heap\'s built in comparison function for comparison.\n\n# Complexity\n- Time complexity:\n$$O(n \\times m \\times log(n \\times m))$$\nThe heap size is bounded by the number of walls, which is equivalent to our "edge" here, as similar to Dijkstra, we never visit an edge twice. And the number of edges in the system is $$2 \\times (n - 1) \\times (m - 1) + (n - 1) + (m - 1)$$ which is roughly $$O(n \\times m)$$\n\n- Space complexity:\n$$O(n \\times m)$$\nThe heap size, plus the result map\n\n# Code\n```python3 []\nimport heapq\n\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n n = len(moveTime)\n m = len(moveTime[0])\n \n # format:\n # (min_dist_arrive_1, min_dist_arrive_2)\n result_map = [[(None, None) for j in range(m)] for i in range(n)]\n result_map[0][0] = (None, 0)\n\n uuid = 0\n # format:\n # (min_dist, uuid, (min_dist_arrive_1, min_dist_arrive_2), (x, y))\n dj_heap = [(0, uuid, (None, 0), (0, 0))]\n\n while len(dj_heap) > 0:\n min_dist, _, dist_array, pos_array = heapq.heappop(dj_heap)\n\n dist_1, dist_2 = dist_array\n x, y = pos_array\n\n if (x, y) == (n - 1, m - 1):\n return min_dist\n\n for delta_x, delta_y in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n next_x = x + delta_x\n next_y = y + delta_y\n\n if next_x < n and next_y < m and next_x >= 0 and next_y >= 0: \n new_dist_1 = None\n new_dist_2 = None\n\n if dist_1 is not None:\n new_dist_2 = max(dist_1 + 2, moveTime[next_x][next_y] + 2)\n if dist_2 is not None:\n new_dist_1 = max(dist_2 + 1, moveTime[next_x][next_y] + 1)\n \n new_min_dist = self.adaptiveMin(new_dist_1, new_dist_2)\n\n old_dist_1, old_dist_2 = result_map[next_x][next_y]\n\n if self.adpativeSmall(new_dist_1, old_dist_1) or self.adpativeSmall(new_dist_2, old_dist_2):\n uuid += 1\n\n heapq.heappush(dj_heap, (new_min_dist, uuid, (new_dist_1, new_dist_2), (next_x, next_y)))\n\n result_map[next_x][next_y] = (self.adaptiveMin(new_dist_1, old_dist_1), self.adaptiveMin(new_dist_2, old_dist_2))\n\n\n def adaptiveMin(self, x1, x2):\n if x1 is None:\n return x2\n if x2 is None:\n return x1\n return min(x1, x2)\n\n def adpativeSmall(self, x1, x2):\n if x1 is None and x2 is None:\n return False\n if x1 is None:\n return False\n if x2 is None:\n return True\n return x1 < x2\n``` | 0 | 0 | ['Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | C++ | Dijkstra | c-dijkstra-by-pikachuu-oul3 | Code\ncpp []\nclass Solution {\n struct comp {\n bool operator()(auto &A, auto &B) {\n return A.first > B.first;\n }\n };\npublic | pikachuu | NORMAL | 2024-11-05T21:09:15.495084+00:00 | 2024-11-05T21:09:15.495110+00:00 | 2 | false | # Code\n```cpp []\nclass Solution {\n struct comp {\n bool operator()(auto &A, auto &B) {\n return A.first > B.first;\n }\n };\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n priority_queue<pair<int, vector<int>>, vector<pair<int, vector<int>>>, comp> PQ;\n PQ.push({0, {0, 0, 0}});\n int n = moveTime.size(), m = moveTime[0].size();\n vector<vector<int>> dist(n, vector<int>(m, INT_MAX));\n pair<int, int> dirs[4] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};\n while(!PQ.empty()) {\n auto curr = PQ.top();\n PQ.pop();\n int currX = curr.second[0], currY = curr.second[1];\n if(currX == n - 1 && currY == m - 1) return curr.first;\n for(auto dir: dirs) {\n int nextX = currX + dir.first, nextY = currY + dir.second;\n if(nextX < 0 || nextY < 0 || nextX >= n || nextY >= m) continue;\n int cost = max(curr.first, moveTime[nextX][nextY]) + 1 + curr.second[2]; \n if(cost < dist[nextX][nextY]) {\n dist[nextX][nextY] = cost;\n PQ.push({cost, {nextX, nextY, (curr.second[2] + 1) % 2}});\n }\n }\n }\n return dist[n - 1][m - 1];\n }\n};\n``` | 0 | 0 | ['Graph', 'Heap (Priority Queue)', 'Matrix', 'Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Can someone please explain why this solution is getting TLE? | can-someone-please-explain-why-this-solu-578a | \nq=[]\nheapq.heapify(q)\nheapq.heappush(q,[0,0,0,True])\nm=len(moveTime)\nn=len(moveTime[0])\nans=[[float(\'inf\') for i in range(n)] for j in range(m)]\nwhile | Varad | NORMAL | 2024-11-05T13:37:18.195653+00:00 | 2024-11-05T13:37:18.195684+00:00 | 11 | false | ```\nq=[]\nheapq.heapify(q)\nheapq.heappush(q,[0,0,0,True])\nm=len(moveTime)\nn=len(moveTime[0])\nans=[[float(\'inf\') for i in range(n)] for j in range(m)]\nwhile(len(q)>0):\n i,j,wt,pre=heapq.heappop(q)\n\n ans[i][j]=min(ans[i][j],wt)\n if i+1<m :\n if pre==True:\n tmp=max(0,moveTime[i+1][j]-wt)+1+wt\n if tmp<ans[i+1][j]:\n heapq.heappush(q,[i+1,j,tmp,False])\n\n else:\n tmp=max(0,moveTime[i+1][j]-wt)+2+wt\n if tmp<ans[i+1][j]:\n heapq.heappush(q,[i+1,j,tmp,True])\n if j+1<n :\n if pre==True:\n tmp=max(0,moveTime[i][j+1]-wt)+1+wt\n if tmp<ans[i][j+1]:\n heapq.heappush(q,[i,j+1,tmp,False])\n\n else:\n tmp=max(0,moveTime[i][j+1]-wt)+2+wt\n if tmp<ans[i][j+1]:\n heapq.heappush(q,[i,j+1,tmp,True])\n\n if i-1>=0:\n if pre==True:\n tmp=max(0,moveTime[i-1][j]-wt)+1+wt\n if tmp<ans[i-1][j]:\n heapq.heappush(q,[i-1,j,tmp,False])\n\n else:\n tmp=max(0,moveTime[i-1][j]-wt)+2+wt\n if tmp<ans[i-1][j]:\n heapq.heappush(q,[i-1,j,tmp,True])\n\n if j-1>=0 :\n if pre==True:\n tmp=max(0,moveTime[i][j-1]-wt)+1+wt\n if tmp<ans[i][j-1]:\n heapq.heappush(q,[i,j-1,tmp,False])\n\n else:\n tmp=max(0,moveTime[i][j-1]-wt)+2+wt\n if tmp<ans[i][j-1]:\n heapq.heappush(q,[i,j-1,tmp,True])\nreturn ans[-1][-1]\n```\n\nTC - \n```\n[[0,88,52,40,24,11,82,54,52,5,24,77,58,37,37,54,24,97,54,79],[81,92,0,9,63,19,98,28,93,38,71,47,29,30,41,47,17,81,33,46],[48,7,84,50,85,80,32,99,74,68,42,88,59,87,23,80,8,42,68,31],[40,45,86,84,69,19,85,52,0,41,8,22,5,56,16,23,9,16,56,50],[2,72,9,73,84,54,3,44,39,14,94,44,5,24,50,73,27,9,90,70],[87,0,16,24,45,97,51,99,25,54,43,75,21,71,81,66,0,81,59,45],[52,51,92,68,88,100,27,52,43,1,100,83,38,51,13,11,30,39,52,51],[51,65,30,69,29,13,1,58,1,73,87,80,71,11,16,64,38,13,84,34],[10,21,83,24,49,36,23,15,91,16,77,98,79,85,48,15,18,89,34,8],[20,34,27,43,39,91,94,19,92,71,22,42,76,58,5,91,61,64,59,75],[57,49,9,1,34,81,99,16,28,61,88,3,27,45,56,91,53,67,33,0]]\n\n``` | 0 | 0 | [] | 0 |
find-minimum-time-to-reach-last-room-ii | Using Priority_Queue || C++ | using-priority_queue-c-by-vijay_kunigiri-i9hs | 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 | vijay_kunigiri17 | NORMAL | 2024-11-05T13:33:09.987423+00:00 | 2024-11-05T13:33:09.987457+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>&grid) {\n int n=grid.size();\n int m=grid[0].size();\n vector<int>dr={-1,0,1,0};\n vector<int>dc={0,1,0,-1};\n priority_queue<pair<int,pair<int,pair<int,int>>>,vector<pair<int,pair<int,pair<int,int>>>>,greater<pair<int,pair<int,pair<int,int>>>>>q;\n vector<vector<int>>dist(n,vector<int>(m,INT_MAX));\n q.push({0,{0,{0,0}}});\n while(!q.empty()){\n int d=q.top().first;\n int adj=q.top().second.first;\n int r=q.top().second.second.first;\n int c=q.top().second.second.second;\n q.pop();\n for(int i=0;i<4;i++){\n int rr=r+dr[i];\n int cc=c+dc[i];\n if(rr>=0 && rr<n && cc>=0 && cc<m){\n int maxi=max(d,grid[rr][cc]);\n if(adj==0){\n if(1+maxi<dist[rr][cc]){\n dist[rr][cc]=1+maxi;\n q.push({dist[rr][cc],{1,{rr,cc}}});\n }\n }\n else{\n if(2+maxi<dist[rr][cc]){\n dist[rr][cc]=2+maxi;\n q.push({dist[rr][cc],{0,{rr,cc}}});\n }\n }\n }\n \n }\n\n }\n \n return dist[n-1][m-1];\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | [C++] Dijkstra. | c-dijkstra-by-lovebaonvwu-ys47 | \ncpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size();\n int m = moveTime[0].size | lovebaonvwu | NORMAL | 2024-11-05T01:07:38.720649+00:00 | 2024-11-05T01:07:38.720694+00:00 | 1 | false | \n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size();\n int m = moveTime[0].size();\n\n priority_queue<array<int, 4>, vector<array<int, 4>>, greater<>> pq;\n pq.push({0, 0, 0, 1});\n vector<vector<int>> arriveAt(n, vector<int>(m, INT_MAX));\n arriveAt[0][0] = 0;\n\n int dirs[] = {0, 1, 0, -1, 0};\n while (!pq.empty()) {\n auto [curTime, y, x, take] = pq.top();\n pq.pop();\n\n if (y == n - 1 && x == m - 1) {\n return curTime;\n }\n\n for (int k = 0; k < 4; ++k) {\n int dy = y + dirs[k];\n int dx = x + dirs[k + 1];\n\n if (dy < 0 || dy == n || dx < 0 || dx == m) {\n continue;\n }\n\n int newTime = max(moveTime[dy][dx], curTime) + take;\n if (newTime < arriveAt[dy][dx]) {\n arriveAt[dy][dx] = newTime;\n pq.push({newTime, dy, dx, take == 1 ? 2 : 1});\n }\n }\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Swift Solution using Dijkstra's | swift-solution-using-dijkstras-by-liampr-po9j | 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 | liampronan | NORMAL | 2024-11-04T20:37:25.531172+00:00 | 2024-11-04T20:37:25.531204+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(nm*log(nm))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n*m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```swift []\nimport Collections\n\nclass Solution {\n func minTimeToReach(_ moveTime: [[Int]]) -> Int {\n\n var minHeap = Heap<Path>()\n var visitedWithTime = Array(repeating: Array(repeating: Int.max, count: moveTime[0].count), count: moveTime.count)\n \n minHeap.insert(Path(r: 0, c: 0, timePassed: 0, nextMoveCost: 1))\n // [[0,4],[4,4]]\n while let currPath = minHeap.popMin() {\n // print(currPath)\n if currPath.r == moveTime.count - 1 && currPath.c == moveTime[0].count - 1 {\n return currPath.timePassed\n }\n \n for (dR, dC) in [(-1,0), (1,0), (0, -1), (0, 1)] {\n \n let newRow = currPath.r + dR, newCol = currPath.c + dC\n guard (0..<moveTime.count).contains(newRow) && (0..<moveTime[0].count).contains(newCol) else { continue }\n let timeAtNewCell = currPath.timePassed >= moveTime[newRow][newCol] ? currPath.timePassed + currPath.nextMoveCost : moveTime[newRow][newCol] + currPath.nextMoveCost\n // print(timeAtNewCell)\n guard timeAtNewCell < visitedWithTime[newRow][newCol] else { continue }\n // print(newRow, newCol, timeAtNewCell)\n visitedWithTime[newRow][newCol] = timeAtNewCell\n minHeap.insert(Path(r: newRow, c: newCol, timePassed: timeAtNewCell, nextMoveCost: currPath.nextMoveCost == 1 ? 2 : 1 ))\n \n }\n }\n return -1\n }\n}\n\nstruct Path: Comparable, CustomStringConvertible {\n let r: Int\n let c: Int\n let timePassed: Int\n let nextMoveCost: Int\n var description: String { "r: \\(r), c: \\(c), timePassed: \\(timePassed), nextMoveCost: \\(nextMoveCost)" }\n\n static func == (lhs: Self, rhs: Self) -> Bool {\n return lhs.r == rhs.r && lhs.c == rhs.c && lhs.timePassed == rhs.timePassed\n }\n\n static func < (lhs: Self, rhs: Self) -> Bool {\n if lhs.timePassed == rhs.timePassed {\n if rhs.nextMoveCost == rhs.nextMoveCost {\n if lhs.r == rhs.r { return lhs.c < rhs.c }\n return lhs.r < rhs.r \n }\n \n return lhs.nextMoveCost < rhs.nextMoveCost\n }\n return lhs.timePassed < rhs.timePassed\n }\n}\n\n``` | 0 | 0 | ['Swift'] | 0 |
find-minimum-time-to-reach-last-room-ii | PriorityQueue to track the min time used till current location | priorityqueue-to-track-the-min-time-used-jowr | Intuition\n Describe your first thoughts on how to solve this problem. \ncorrectly understand the meaning of "alternating between the two." is the core part of | linda2024 | NORMAL | 2024-11-04T20:19:36.901378+00:00 | 2024-11-04T20:19:36.901415+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncorrectly understand the meaning of "alternating between the two." is the core part of this question.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```csharp []\npublic class Solution {\n public int MinTimeToReach(int[][] moveTime) {\n int[] dir = new int[]{0, 1, 0, -1, 0};\n int row = moveTime.Length, col = moveTime[0].Length, res = int.MaxValue;\n int[,] dp = new int[row, col];\n for(int i = 0; i < row; i++)\n {\n for(int j = 0; j < col; j++)\n {\n dp[i, j] = -1;\n }\n }\n\n PriorityQueue<(int, int, bool), int> que = new();\n que.Enqueue((0, 0, false), 0);\n\n while(que.Count > 0)\n {\n if(que.TryDequeue(out var cur, out int time))\n {\n (int x, int y, bool alter) = cur;\n\n if(time >= res || dp[x, y] >= 0 && dp[x, y] <= time)\n continue;\n\n dp[x, y] = time;\n for(int p = 0; p < 4; p++)\n {\n int newX = x + dir[p], newY = y + dir[p+1];\n if(newX < 0 || newY < 0 || newX >= row || newY >= col)\n continue;\n\n int newTime = Math.Max(moveTime[newX][newY], time) + (alter ? 2 : 1);\n if(newTime < res)\n {\n if(newX == row-1 && newY == col-1)\n {\n res = Math.Min(res, newTime);\n dp[newX, newY] = Math.Min(dp[newX, newY], newTime);\n }\n else\n que.Enqueue((newX, newY, !alter), newTime);\n }\n }\n } \n }\n\n return res;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra | C++ | dijkstra-c-by-siddharth96shukla-2v3t | Complexity\n- Time complexity: O(nm*log(nm))\n Add your time complexity here, e.g. O(n) \n\n# Code\ncpp []\n#define ll long long int\n\nclass Solution {\npublic | siddharth96shukla | NORMAL | 2024-11-04T17:52:26.547639+00:00 | 2024-11-04T17:52:26.547675+00:00 | 14 | false | # Complexity\n- Time complexity: $$O(nm*log(nm))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define ll long long int\n\nclass Solution {\npublic:\n int dr[4] = {0, 1, 0, -1};\n int dc[4] = {1, 0, -1, 0};\n\n int minTimeToReach(vector<vector<int>>& mt) {\n int n=mt.size(), m=mt[0].size();\n priority_queue<vector<ll>, vector<vector<ll>>, greater<vector<ll>>>pq;\n vector<vector<ll>>dist(n, vector<ll>(m, LLONG_MAX));\n dist[0][0]=0;\n pq.push({0, 0, 0, 2});\n while(!pq.empty()){\n auto t = pq.top();\n pq.pop();\n ll d = t[0];\n int x=t[1], y=t[2], c=t[3];\n if(x==n-1 && y==m-1)return d;\n if(d>dist[x][y])continue;\n for(int i=0;i<4;i++){\n int nx=x+dr[i], ny=y+dc[i];\n if(nx>=0 && nx<n && ny>=0 && ny<m){\n ll k = max((ll)0, mt[nx][ny]-d);\n if(c==2)k+=1;\n else k+=2;\n if(dist[nx][ny] > (d + k)){\n dist[nx][ny]= (d + k);\n if(c==2)pq.push({dist[nx][ny], nx, ny, 1});\n else pq.push({dist[nx][ny], nx, ny, 2});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Shortest Path', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Easy and intutive solution | easy-and-intutive-solution-by-coolcoder2-106d | 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 | coolcoder251 | NORMAL | 2024-11-04T17:33:20.784189+00:00 | 2024-11-04T17:33:20.784230+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m=moveTime.size();\n int n=moveTime[0].size();\n\n priority_queue<tuple<int, int, int , int>, vector<tuple<int, int, int, int>>,\n greater<tuple<int, int, int, int>>>pq;\n vector<vector<int>>dist(m, vector<int>(n,INT_MAX));\n pq.push({0,0,0,0});\n\n int dx[]={0,1,0, -1};\n int dy[]={1,0,-1, 0};\n while(!pq.empty()){\n auto [cost, x, y,move]=pq.top();\n pq.pop();\n\n if(x==m-1 && y==n-1) return cost;\n\n for(int i=0;i<4;i++){\n int new_x= x+dx[i];\n int new_y= y+dy[i];\n\n if(new_x>=0&&new_x<m&& new_y>=0&&new_y<n){\n int val=max(cost,moveTime[new_x][new_y])+(move%2==0?1:2);\n if(val<dist[new_x][new_y]){\n dist[new_x][new_y]=val;\n pq.emplace(val, new_x, new_y, 1-(move&1));\n }\n }\n }\n }\n return -1;\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Djkistra Algorithm | djkistra-algorithm-by-stwik_back-oaxr | Intuition\nFirst thoght is of Dynamic programming.But it is very Compliacted because we have four directions to move so there is a possibility of cycle and if w | stwik_back | NORMAL | 2024-11-04T17:17:46.753428+00:00 | 2024-11-04T17:17:46.753468+00:00 | 23 | false | # Intuition\nFirst thoght is of Dynamic programming.But it is very Compliacted because we have four directions to move so there is a possibility of cycle and if we do dp we need to handle the cycle also. so think of graph algorithms.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nso the approach is using Djkistra algo. where we need to store three states i,j,move .move is to check whether it is even or odd .\nto check even or odd i am taking xor with 1.and simply applying Djkistra Algorithm\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n int directions[][]={{1,0},{0,1},{-1,0},{0,-1}};\n public int minTimeToReach(int[][] moveTime) {\n int m=moveTime.length;\n int n=moveTime[0].length;\n\n int dis[][][]=new int [m][n][2];\n for(int row[][]:dis){\n for(int r[]:row){\n Arrays.fill(r,Integer.MAX_VALUE);\n }\n }\n dis[0][0][0]=0;\n PriorityQueue<int[]> pq =new PriorityQueue<>(Comparator.comparingInt(a->a[0]));\n pq.offer(new int[]{0,0,0,0});\n while(!pq.isEmpty()){\n int nu[]=pq.poll();\n int dist=nu[0];\n int i=nu[1];\n int j=nu[2];\n int move=nu[3];\n int cost=(move%2==0?true:false)?1:2;\n for(int dir[]:directions){\n int newi=i+dir[0];\n int newj=j+dir[1];\n int nextmove=(move ^1);\n if(newi>=0 && newj>=0 && newi<m && newj<n && dis[newi][newj][nextmove]>Math.max((dis[i][j][move]+cost),moveTime[newi][newj]+cost)){\n dis[newi][newj][nextmove]=Math.max((dis[i][j][move]+cost),moveTime[newi][newj]+cost);\n\n pq.offer(new int[]{dis[newi][newj][nextmove],newi,newj,nextmove});\n\n }\n }\n \n }\n return Math.min(dis[m-1][n-1][0],dis[m-1][n-1][1]);\n }\n}\n``` | 0 | 0 | ['Graph', 'Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Simple bfs solution | simple-bfs-solution-by-risabhuchiha-pi0u | \njava []\nclass Solution {\n public int minTimeToReach(int[][] m) {\n PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->a[2]-b[2]);\n pq.off | risabhuchiha | NORMAL | 2024-11-04T14:25:28.948285+00:00 | 2024-11-04T14:25:28.948315+00:00 | 6 | false | \n```java []\nclass Solution {\n public int minTimeToReach(int[][] m) {\n PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->a[2]-b[2]);\n pq.offer(new int[]{0,0,0,0});\n int[][]vis=new int[m.length][m[0].length];\n int[]dr=new int[]{0,1,0,-1};\n int[]dc=new int[]{1,0,-1,0};\n vis[0][0]=1;\n while(pq.size()>0){\n int[]x=pq.poll(); \n if(x[0]==m.length-1&&x[1]==m[0].length-1)return x[2];\n for(int i=0;i<4;i++){\n int nr=dr[i]+x[0];\n int nc=dc[i]+x[1];\n if(nr<m.length&&nr>=0&&nc>=0&&nc<m[0].length&&vis[nr][nc]==0){\n vis[nr][nc]=1;\n if(x[3]==1){\n pq.offer(new int[]{nr,nc,Math.max(x[2],m[nr][nc])+2,2});\n }\n else{\n pq.offer(new int[]{nr,nc,Math.max(x[2],m[nr][nc])+1,1}); \n }\n // if(nr==m.length-1&&nc==m[0].length-1)return ,Math.max(x[2],m[nr][nc])+1;\n }\n } \n }\n return -1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | Explanation for bigenners | Dikstra using priority queue | explanation-for-bigenners-dikstra-using-bufkb | Approach\n Describe your approach to solving the problem. \n## 1. Problem Setup\nYou\u2019re given a grid (mt) where each cell has a time requirement. You need | goku_monkey | NORMAL | 2024-11-04T14:22:59.631816+00:00 | 2024-11-04T14:22:59.631855+00:00 | 7 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n## 1. Problem Setup\nYou\u2019re given a grid (mt) where each cell has a time requirement. You need to find the minimum time to reach the bottom-right corner from the top-left corner, but you may have to wait if the time isn\u2019t right to move to a cell.\n## 2. Priority Queue for Shortest Path:\n\nThe code uses a priority queue (similar to a line where the shortest distance is served first) to explore the grid. This helps find the quickest way to reach each cell in the grid, based on the shortest time seen so far.\n## 3. Distance Matrix:\n\nA dist matrix tracks the shortest time required to reach each cell. Initially, every cell is set to a very large number (INT_MAX), except for the starting cell (0,0), which is set to 0 because it\u2019s the starting point.\n## 4. Processing Cells:\n\nStart from the top-left cell. For each cell, the code:\nChecks all 4 possible directions (right, down, left, and up).\nFor each neighboring cell, two possibilities are considered:\nDirect Move: If you can directly move into the neighboring cell without waiting, update the dist matrix with the new, shorter time.\nWait Move: If you can\u2019t enter immediately (because the cell\u2019s required time hasn\u2019t been met), wait until it\u2019s available, then update the distance.\n## 5. Toggle Timing:\n\nEach time you move, you alternate the step count z (either 1 or 2). This helps handle the "wait time" in some cells so that it accurately reflects when you\u2019d actually arrive.\n## 6. Updating Queue:\n\nAfter calculating a possible time for each neighboring cell, push it into the queue to explore it further. This process continues until the priority queue is empty, which means all cells have been explored with the shortest possible time.\n## 7. Final Result:\n\nWhen you reach the bottom-right corner, the dist[n-1][m-1] value gives you the minimum time required to reach the end of the grid.\n\n# Complexity\n- Time complexity:$$O(n*mlog(n*m))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n*m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define pi pair<int,int>\nbool comp(vector<int> &a, vector<int> &b){\n // Custom comparator for priority queue to sort by time in descending order\n return a[3] > b[3];\n}\n\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& mt) {\n // Priority queue to process cells in order of shortest time, with custom comparator\n priority_queue<vector<int>, vector<vector<int>>, decltype(&comp)> q(&comp);\n\n // Direction vectors for moving right, down, left, and up\n vector<vector<int>> dir = {{0,1}, {1,0}, {-1,0}, {0,-1}};\n \n // Start from top-left corner with initial time set to 1\n q.push({0, 0, 1});\n \n int n = size(mt), m = size(mt[0]);\n \n // Distance matrix to store the minimum time to reach each cell\n vector<vector<int>> dist(n, vector<int>(m, INT_MAX));\n dist[0][0] = 0;\n\n // Process each cell in priority order\n while(!q.empty()) {\n auto cur = q.top();\n q.pop();\n int x = cur[0], y = cur[1], z = cur[2]; // Extract current cell and time\n \n // If we\'ve reached the bottom-right corner, exit\n if(x == n - 1 && y == m - 1) break;\n\n // Check each direction from the current cell\n for(int i = 0; i < 4; i++) {\n int a = x + dir[i][0], b = y + dir[i][1];\n\n // Skip cells out of grid bounds\n if(a < 0 || b < 0 || a >= n || b >= m) continue;\n\n // Case 1: If we can move directly to the cell without waiting\n if(mt[a][b] <= dist[x][y] && dist[a][b] > dist[x][y] + z) {\n dist[a][b] = dist[x][y] + z; // Update minimum time\n int k = (z == 1) ? 2 : 1; // Alternate wait time for next step\n q.push({a, b, k, dist[a][b]});\n }\n // Case 2: If we need to wait to enter the cell\n else if(mt[a][b] > dist[x][y] && dist[a][b] > mt[a][b] + z) {\n dist[a][b] = min(dist[a][b], mt[a][b] + z); // Update minimum time with wait\n int k = (z == 1) ? 2 : 1; // Alternate wait time for next step\n q.push({a, b, k, dist[a][b]});\n }\n }\n }\n\n // Return the minimum time to reach bottom-right corner\n return dist[n - 1][m - 1];\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Beats 100%(Easy to understand) | beats-100easy-to-understand-by-ayushjha1-wn5e | Intuition\nSame as Previos question just apply step logic\n# Approach\nMaintain a third variable for step and toggle it between 1 and 2 which can be done as 3-s | ayushjha11 | NORMAL | 2024-11-04T13:29:32.397026+00:00 | 2024-11-04T13:29:32.397070+00:00 | 4 | false | # Intuition\nSame as Previos question just apply step logic\n# Approach\nMaintain a third variable for step and toggle it between 1 and 2 which can be done as 3-step\n\n# Complexity\n- Time complexity:\nO(N\u2217M\u2217Log(N+M))\n\n- Space complexity:\nO(N\u2217M)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int n = moveTime.size();\n int m = moveTime[0].size();\n vector<vector<int>> minTime(n, vector<int>(m, INT_MAX));\n \n \n priority_queue<tuple<int, int, int, int>, vector<tuple<int, int, int, int>>, greater<>> pq;\n \n pq.push({0, 0, 0, 1}); \n minTime[0][0] = 0;\n\n vector<pair<int, int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n\n while (!pq.empty()) {\n auto [currTime, x, y, step] = pq.top();\n pq.pop();\n\n if (x == n - 1 && y == m - 1) return currTime;\n\n for (auto& dir : directions) {\n int nx = x + dir.first;\n int ny = y + dir.second;\n\n if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;\n\n // int waitTime = max(0, moveTime[nx][ny] - currTime);\n int nextTime = max(moveTime[nx][ny] , currTime)+step;\n int nextStep = 3 - step;\n\n if (nextTime < minTime[nx][ny]) {\n minTime[nx][ny] = nextTime;\n pq.push({nextTime, nx, ny, nextStep});\n }\n }\n }\n\n return -1; \n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | beat 100%||classical dijkstra algorithm | beat-100classical-dijkstra-algorithm-by-l3bly | 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 | sachinkumar993426 | NORMAL | 2024-11-04T13:12:12.833898+00:00 | 2024-11-04T13:12:12.833942+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n int minTimeToReach(vector<vector<int>>& mt) {\n// priority_queue--->{dist,{step,{curr_x,curr_y}}};\n priority_queue<pair<int,pair<int,pair<int,int>>>, vector<pair<int,pair<int,pair<int,int>>>>, greater<pair<int,pair<int,pair<int,int>>>>> pq;\n pq.push({0,{1 ,{0, 0}}});\n int n = mt.size();\n int m = mt[0].size();\n vector<vector<int>> dp(n, vector<int>(m, INT_MAX));\n int dx[] = {-1, 1, 0, 0};\n int dy[] = {0, 0, -1, 1};\n dp[0][0] = 0;\n \n while (!pq.empty()) {\n auto node = pq.top(); pq.pop();\n int ty = node.second.first;\n int x = node.second.second.first;\n int y= node.second.second.second;\n int d = node.first;\n \n // If we reached the bottom-right corner\n if (x == n - 1 && y == m - 1) return d;\n \n // Explore the four possible directions\n for (int i = 0; i < 4; i++) {\n int nx = x + dx[i];\n int ny = y + dy[i];\n \n // Skip out-of-bounds cells\n if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;\n \n // Calculate the time needed to reach the cell (nx, ny)\n int curr = ty + max(d, mt[nx][ny]);\n \n // If this new time is less than the previously stored time\n if (curr < dp[nx][ny]) {\n dp[nx][ny] = curr;\n pq.push({curr,{ty^3 ,{nx, ny}}});\n }\n }\n }\n \n return dp[n - 1][m - 1];\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra Algo | Easy | C++ | Beats 90% | Graph | dijkstra-algo-easy-c-beats-90-graph-by-b-vym7 | \n# Code\ncpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m = moveTime.size();\n int n = moveTime | bkbkbhavyakalra | NORMAL | 2024-11-04T12:25:45.501230+00:00 | 2024-11-04T12:25:45.501255+00:00 | 4 | false | \n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) {\n int m = moveTime.size();\n int n = moveTime[0].size();\n priority_queue<pair<int,vector<int>>, vector<pair<int,vector<int>>>, greater<pair<int,vector<int>>>> pq;\n vector<vector<int>> check(m,vector<int>(n,INT_MAX));\n int dx[4] = {-1,0,1,0};\n int dy[4] = {0,1,0,-1};\n pq.push({0, {0,0,1}});\n while(!pq.empty()){\n auto it = pq.top();\n pq.pop();\n int cx = it.second[0];\n int cy = it.second[1];\n int cp = it.second[2];\n if(cx == m-1 && cy == n-1){\n return it.first;\n }\n int cw = it.first;\n for(int i = 0; i < 4; i++){\n int nx = cx + dx[i];\n int ny = cy + dy[i];\n if(nx >= m || nx < 0 || ny >= n || ny < 0){\n continue;\n }\n int nw = max(cw, moveTime[nx][ny]) + cp;\n if(nw < check[nx][ny]){\n check[nx][ny] = nw;\n if(cp == 1){\n pq.push({nw,{nx,ny,2}});\n }else{\n pq.push({nw,{nx,ny,1}});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Array', 'Graph', 'Matrix', 'C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | Concise and easiy to follow solution using dp and heap | concise-and-easiy-to-follow-solution-usi-5art | Intuition\nInspired by many solutions from question: Find Minimum Time to Reach Last Room I\n\n# Approach\nUsing minheap to follow the path that has minimum tim | nguyenhuuthai | NORMAL | 2024-11-04T11:45:29.486040+00:00 | 2024-11-04T11:45:29.486064+00:00 | 10 | false | # Intuition\nInspired by many solutions from question: [Find Minimum Time to Reach Last Room I](https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/description/)\n\n# Approach\nUsing minheap to follow the path that has minimum time\nUsing dp to store the minimum time to get to a specific node(dungeon)\nif we reach the end of the matrix, we immidiately return the result\n\n\n# Code\n```python3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n #i set the first node to be -1 because we start with 0 time, and later in the code i will add 1 so it becomes 0\n moveTime[0][0] = -1\n #our min heap, (curTime,x,y,curStep)\n queue = [(-1,0,0,0)]\n lenN = len(moveTime)\n lenM = len(moveTime[0])\n dp = [[float(\'inf\')]*lenM for _ in range(lenN)]\n\n while queue:\n curTime, x, y,curStep = heappop(queue)\n\n #only continue if we are in the matrix\n if 0<=x<lenN and 0<=y<lenM:\n \n curTime = max(curTime, moveTime[x][y])+ curStep\n\n #switch step\n if curStep == 1:\n curStep = 2\n else:\n curStep = 1\n\n if (x,y) == (lenN-1,lenM-1):\n return curTime\n\n #if we meet a better way, we update the dp and add its adjacent nodes to the queue\n if curTime<dp[x][y]:\n dp[x][y] = curTime\n heappush(queue,(curTime,x+1,y,curStep))\n heappush(queue,(curTime,x-1,y,curStep))\n heappush(queue,(curTime,x,y+1,curStep))\n heappush(queue,(curTime,x,y-1,curStep))\n\n``` | 0 | 0 | ['Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Dijkstra | dijkstra-by-user5285zn-ylyd | rust []\nuse std::collections::BinaryHeap;\nuse std::cmp::Reverse;\n\nimpl Solution {\n pub fn min_time_to_reach(move_time: Vec<Vec<i32>>) -> i32 {\n | user5285Zn | NORMAL | 2024-11-04T10:52:41.959964+00:00 | 2024-11-04T10:52:41.959990+00:00 | 6 | false | ```rust []\nuse std::collections::BinaryHeap;\nuse std::cmp::Reverse;\n\nimpl Solution {\n pub fn min_time_to_reach(move_time: Vec<Vec<i32>>) -> i32 {\n let n = move_time.len();\n let m = move_time[0].len();\n let mut q = BinaryHeap::new();\n let mut seen = vec![vec![false; m]; n];\n q.push((Reverse(0),1,0,0));\n seen[0][0] = true;\n while let Some((Reverse(t), x, i, j)) = q.pop() {\n if (i,j) == (n-1, m-1) {return t }\n for (i,j) in [(i+1, j), (i.wrapping_sub(1),j), (i, j+1), (i, j.wrapping_sub(1))] {\n if i >= n || j >= m || seen[i][j] {continue}\n seen[i][j] = true;\n q.push((Reverse(x+t.max(move_time[i][j])), 3-x, i, j))\n }\n }\n unreachable!()\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
find-minimum-time-to-reach-last-room-ii | Djikstra Solution. | djikstra-solution-by-arif2321-wl8l | 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 | Arif2321 | NORMAL | 2024-11-04T10:21:29.804573+00:00 | 2024-11-04T10:21:29.804606+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minTimeToReach(vector<vector<int>>& moveTime) \n {\n int n = moveTime.size();\n int m = moveTime[0].size();\n vector<vector<long long>> dis(n,vector<long long>(m,1e12));\n priority_queue<pair<pair<int,int>,pair<int,int>>,vector<pair<pair<int,int>,pair<int,int>>>,greater<pair<pair<int,int>,pair<int,int>>>> pq;\n pq.push({{0,0},{0,0}});\n dis[0][0] = 0;\n vector<pair<int,int>> v = {{1,0},{-1,0},{0,1},{0,-1}};\n while(!pq.empty())\n {\n auto node = pq.top();\n pq.pop();\n int t = node.first.first;\n int mv = node.first.second;\n int i = node.second.first;\n int j = node.second.second;\n // cout << t << " " << i << " " << j << endl;\n for(auto it : v)\n {\n int r = i+it.first;\n int c = j+it.second;\n if(r >= n || c >= m || r < 0 || c < 0) continue;\n if(dis[r][c] > (max(1LL*moveTime[r][c],dis[i][j]) + (mv == 0 ? 1 : 2)))\n {\n dis[r][c] = (max(1LL*moveTime[r][c],dis[i][j]) + (mv == 0 ? 1 : 2));\n pq.push({{dis[r][c],mv^1},{r,c}});\n }\n }\n }\n return dis[n-1][m-1];\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-minimum-time-to-reach-last-room-ii | JAVA solution with simple calculation of moving time | java-solution-with-simple-calculation-of-ae24 | Intuition\n Describe your first thoughts on how to solve this problem. \nwhen current cell is (i,j), the moving time is (i+j)%2+1.\n\n\n# Approach\n Describe yo | meringueee | NORMAL | 2024-11-04T10:15:21.488777+00:00 | 2024-11-04T10:15:21.488799+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwhen current cell is (i,j), the moving time is (i+j)%2+1.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minTimeToReach(int[][] t) {\n final int[][] r = {{1,0},{-1,0},{0,1},{0,-1}};\n int n=t.length;\n int m=t[0].length;\n\n int[][] d = new int[n][m];\n for(int i=0; i<n; i++)Arrays.fill(d[i], 2_000_000_000);\n d[0][0]=0;\n\n PriorityQueue<node> q = new PriorityQueue<>();\n q.add(new node(0,0,0));\n\n int ni, nj, nv;\n while(!q.isEmpty()){\n node cur = q.poll();\n if(cur.v>d[cur.i][cur.j])continue;\n\n for(int[] rr:r){\n ni=cur.i+rr[0]; nj=cur.j+rr[1];\n if(ni<0||ni>=n||nj<0||nj>=m)continue;\n nv=Math.max(cur.v, t[ni][nj])+(cur.i+cur.j)%2 +1;\n\n if(nv<d[ni][nj]){\n d[ni][nj]=nv; q.add(new node(ni,nj,nv));\n }\n }\n }\n return d[n-1][m-1];\n }\n class node implements Comparable<node>{\n int i, j, v;\n node(int _i, int _j, int _v){\n i=_i; j=_j; v=_v;\n }\n @Override\n public int compareTo(node o){\n return Integer.compare(this.v, o.v);\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | JAVA DP + PQ SOLUTION | java-dp-pq-solution-by-divyansh_2069-hu4m | 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 | divyansh_2069 | NORMAL | 2024-11-04T09:13:06.746644+00:00 | 2024-11-04T09:13:06.746669+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n static class Pair implements Comparable<Pair>{\n int x;\n int y;\n int time;\n int breakt;\n public Pair(int i, int j, int t,int b){\n this.x=i;\n this.y=j;\n this.time=t;\n this.breakt=b;\n }\n\n @Override \n public int compareTo(Pair p2){\n return this.time-p2.time;\n }\n }\n public int minTimeToReach(int[][] moveTime) {\n int n=moveTime.length;\n int m=moveTime[0].length;\n\n int dp[][]= new int [n][m];\n \n int[] dx = {1, 0, -1, 0};\n int[] dy = {0, -1, 0, 1};\n \n PriorityQueue<Pair> pq= new PriorityQueue<>();\n pq.add(new Pair(0,0,0,1)); \n\n for(int k=0;k<n;k++){\n Arrays.fill(dp[k],Integer.MAX_VALUE);\n }\n\n dp[0][0] =0; \n \n while(!pq.isEmpty()) {\n Pair curr = pq.remove();\n int x = curr.x;\n int y = curr.y;\n int time = curr.time;\n int br= curr.breakt;\n\n for(int i=0;i<4;i++) {\n int nx = x + dx[i];\n int ny = y + dy[i];\n\n if(nx >= 0 && nx < n && ny >= 0 && ny < m) {\n int nextTime = time+br;\n int nextBreak =(br == 1) ? 2 : 1;\n\n if (time >= moveTime[nx][ny]) { \n if (dp[nx][ny] > nextTime) {\n dp[nx][ny] = nextTime;\n pq.add(new Pair(nx, ny, nextTime, nextBreak));\n }\n } else { \n int waitTime = moveTime[nx][ny] + br;\n if (dp[nx][ny]>waitTime) {\n dp[nx][ny]=waitTime;\n pq.add(new Pair(nx, ny, waitTime, nextBreak));\n }\n }\n \n \n }\n }\n }\n\n \n return dp[n-1][m-1];\n \n }\n\n \n}\n\n``` | 0 | 0 | ['Java'] | 0 |
find-minimum-time-to-reach-last-room-ii | BFS | Min Heap | 100% (Space & Time) | bfs-min-heap-100-space-time-by-hieuwu-8uqq | Recommended problems to get familiar with BFS & Min Heap\n\n3341. Find Minimum Time to Reach Last Room I\n2577. Minimum Time to Visit a Cell In a Grid\n\n# Intu | hieuwu | NORMAL | 2024-11-04T08:02:18.955652+00:00 | 2024-11-04T08:02:18.955681+00:00 | 22 | false | Recommended problems to get familiar with BFS & Min Heap\n\n[3341. Find Minimum Time to Reach Last Room I](https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/)\n[2577. Minimum Time to Visit a Cell In a Grid](https://leetcode.com/problems/minimum-time-to-visit-a-cell-in-a-grid)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find minimum time to reach last room (aka room at [m-1][n-1]), we need to go to that room, starting from [0][0]. As we go through each room, we need to calculate at which time we get there.\nFor each step, it takes us 1 second or 2 second interleavely\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialize a move array containing possible horizontal & vertical move\nInitialize a visited set to mark positions already are visited\nInitialize a min heap with initial value (0, 0, 0, 0) indicates (time, row, col, count)\nWith:\n- `time`: current time to get to that row, col\n- `row`, `col`: current position\n- `count`: number of steps\nImplement `isValid` function to validate a row, column should be visited or not.\n\nWhile heap is not empty:\nGet last element of heap. \nIf current position is at last room, return time\nIterate over moves array:\n - For each move, calculate adjecent row `adjx` and adjeccent column `adjy`. If this position is valid, calculate `altTime` based on count value. Then push `newTime`, `adjx`, `adjy`, `count + 1` into heap.\n - `newTime` is calculated by using max calue of moveTime at the position and current time, plus altTime\n - Mark `adjx`, `adjy` visited\n\n# Complexity\n- Time complexity: O(m * n * log(m*n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m * n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n moves = [\n [0, 1],\n [1, 0],\n [0, -1],\n [-1, 0]\n ]\n heap = [(0, 0, 0, 0)]\n visited = set((0, 0))\n numRows, numCols = len(moveTime), len(moveTime[0])\n def isValid(row, col):\n return (\n 0 <= row < numRows\n and 0 <= col < numCols\n and (row, col) not in visited\n )\n while heap:\n time, row, col, count = heapq.heappop(heap)\n if row == numRows - 1 and col == numCols - 1:\n return time\n for x, y in moves:\n adjx = row + x\n adjy = col + y\n if isValid(adjx, adjy):\n altTime = 1 if (count % 2 == 0) else 2\n newTime = max(moveTime[adjx][adjy], time) + altTime\n heappush(heap, (newTime, adjx, adjy, count + 1))\n visited.add((adjx, adjy))\n \n return -1\n``` | 0 | 0 | ['Breadth-First Search', 'Heap (Priority Queue)', 'Python3'] | 0 |
find-minimum-time-to-reach-last-room-ii | Solution using Dijkstra Algorithm | solution-using-dijkstra-algorithm-by-adi-hvdl | \n# Code\npython3 []\nclass Solution:\n # solved using dijkstra\'s algorithm, Time complexity: O(Elog(V))\n def minTimeToReach(self, moveTime: List[List[i | adityabhattad18 | NORMAL | 2024-11-04T07:03:23.634616+00:00 | 2024-11-04T07:03:23.634652+00:00 | 14 | false | \n# Code\n```python3 []\nclass Solution:\n # solved using dijkstra\'s algorithm, Time complexity: O(Elog(V))\n def minTimeToReach(self, moveTime: List[List[int]]) -> int:\n ROW,COL = len(moveTime), len(moveTime[0])\n directions = [\n (-1,0),\n (1,0),\n (0,-1),\n (0,1)\n ]\n opp = lambda x: 1 if x == 0 else 0\n # cost,row,col,add (to handle "takes one second for one move and two seconds for the next, alternating between the two" part)\n queue = []\n heapq.heappush(queue,(0,0,0,0))\n visited = set()\n\n while len(queue) != 0:\n cost,row,col,add = heapq.heappop(queue)\n if row == ROW-1 and col == COL-1:\n return cost\n if (row,col) in visited:\n continue\n\n visited.add((row,col))\n for dx,dy in directions:\n new_row = row + dx\n new_col = col + dy\n if (0<=new_row<ROW) and (0<=new_col<COL):\n heapq.heappush(\n queue,\n (\n max(cost,moveTime[new_row][new_col]) + 1 + add,\n new_row,\n new_col,\n opp(add)\n )\n )\n return -1\n``` | 0 | 0 | ['Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.