Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 7, 2025 16:35
Show Gist options
  • Save tatsuyax25/3b65011e37ba5316b8b851efd2bb4062 to your computer and use it in GitHub Desktop.
Save tatsuyax25/3b65011e37ba5316b8b851efd2bb4062 to your computer and use it in GitHub Desktop.
There is a dungeon with n x m rooms arranged as a grid. You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum time in seconds when you can start moving to that room. You start from the room (0, 0) at time t = 0
/**
* Finds the minimum time required to reach the bottom-right cell of the grid.
* Each cell contains a time constraint that dictates the earliest possible arrival.
*
* @param {number[][]} moveTime - A 2D array representing the minimum time required
* to step into each cell.
* @return {number} - The minimum time required to reach the last cell, or -1 if unreachable.
*/
var minTimeToReach = function(moveTime) {
const rows = moveTime.length;
const cols = moveTime[0].length;
// Initialize a grid to keep track of the shortest arrival time for each cell.
const minTimes = Array.from({ length: rows }, () => Array(cols).fill(Infinity));
// Priority queue (sorted by time) for processing cells in increasing order of arrival time.
const priorityQueue = [[0, 0, 0]]; // [time, row, col]
minTimes[0][0] = 0; // Start from the top-left corner with an initial arrival time of 0.
// Possible movement directions: up, down, left, right.
const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
while (priorityQueue.length) {
// Always process the cell with the shortest arrival time first.
priorityQueue.sort((a, b) => a[0] - b[0]);
const [currentTime, currentRow, currentCol] = priorityQueue.shift();
// If we reach the bottom-right cell, return the computed arrival time.
if (currentRow === rows - 1 && currentCol === cols - 1) {
return currentTime;
}
// Explore neighboring cells.
for (const [deltaRow, deltaCol] of directions) {
const nextRow = currentRow + deltaRow;
const nextCol = currentCol + deltaCol;
// Ensure the move stays within the grid boundaries.
if (nextRow >= 0 && nextCol >= 0 && nextRow < rows && nextCol < cols) {
// The earliest possible arrival at the next cell.
const arrivalTime = Math.max(currentTime, moveTime[nextRow][nextCol]) + 1;
// Update if a shorter arrival time is found.
if (arrivalTime < minTimes[nextRow][nextCol]) {
minTimes[nextRow][nextCol] = arrivalTime;
priorityQueue.push([arrivalTime, nextRow, nextCol]);
}
}
}
}
// If the bottom-right cell is unreachable, return -1.
return -1;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment