Last active
November 20, 2021 13:29
-
-
Save ali-master/423699a26d8dbc568158ab0df9a9298e to your computer and use it in GitHub Desktop.
Check if we can go from top-left to the right-bottom in a Matrix which returns the path of way by javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const grid: Array<Array<number>> = [ | |
[1, 0, 1, 1, 1], | |
[1, 1, 1, 0, 0], | |
[0, 1, 0, 1, 1], | |
[1, 0, 1, 1, 0], | |
[0, 0, 1, 1, 1] | |
]; | |
console.log(solveGrid(grid)); | |
function solveGrid<U extends number = number, T extends Array<U> = Array<U>>(matrix: Array<T>): Array<string> { | |
const visited: Array<Array<boolean>> = [...Array.from({ length: matrix.length }, () => [])]; | |
visited[0][0] = true; | |
const route: Array<string> = []; | |
return can(matrix, 0, 0, visited, route); | |
} | |
function can(grid: Array<Array<number>>, x: number, y: number, visited: Array<Array<boolean>>, route: Array<string>): Array<string> { | |
const base = grid[0][0]; | |
if (grid.length - 1 === x && grid[x].length - 1 === y) { | |
return route; | |
} | |
// Top | |
if (grid[x - 1]?.[y] === base && !visited[x - 1][y]) { | |
visited[x - 1][y] = true; | |
route.push("top"); | |
const result = can(grid, x - 1, y, visited, route); | |
if (result) { | |
return result; | |
} | |
} | |
// Right | |
if (grid[x]?.[y + 1] === base && !visited[x][y + 1]) { | |
visited[x][y + 1] = true; | |
route.push("right"); | |
const result = can(grid, x, y + 1, visited, route); | |
if (result) { | |
return result; | |
} | |
} | |
// Left | |
if (grid[x]?.[y - 1] === base && !visited[x][y - 1]) { | |
visited[x][y - 1] = true; | |
route.push("left"); | |
const result = can(grid, x, y - 1, visited, route); | |
if (result) { | |
return result; | |
} | |
} | |
// Down | |
if (grid[x + 1]?.[y] === base && !visited[x + 1][y]) { | |
visited[x + 1][y] = true; | |
route.push("down"); | |
const result = can(grid, x + 1, y, visited, route); | |
if (result) { | |
return result; | |
} | |
} | |
return ['lost']; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment