/*
* Problem Statement:
* - Given a NxN grid, find whether rat in cell [0, 0] can reach the target in cell [N-1, N-1]
* - The grid is represented as an array of rows. Each row is represented as an array of 0 or 1 values.
* - A cell with value 0 can not be moved through. Value 1 means the rat can move here.
* - The rat can not move diagonally.
*
* Reference for this problem: https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/
*
* Based on the original implementation contributed by Chiranjeev Thapliyal (https://github.com/chiranjeev-thapliyal).
*/
/**
* Checks if the given grid is valid.
*
* A grid needs to satisfy these conditions:
* - must not be empty
* - must be a square
* - must not contain values other than {@code 0} and {@code 1}
*
* @param grid The grid to check.
* @throws TypeError When the given grid is invalid.
*/
function validateGrid(grid) {
if (!Array.isArray(grid) || grid.length === 0)
throw new TypeError('Grid must be a non-empty array')
const allRowsHaveCorrectLength = grid.every(
(row) => row.length === grid.length
)
if (!allRowsHaveCorrectLength) throw new TypeError('Grid must be a square')
const allCellsHaveValidValues = grid.every((row) => {
return row.every((cell) => cell === 0 || cell === 1)
})
if (!allCellsHaveValidValues)
throw new TypeError('Grid must only contain 0s and 1s')
}
function isSafe(grid, x, y) {
const n = grid.length
return x >= 0 && x < n && y >= 0 && y < n && grid[y][x] === 1
}
/**
* Attempts to calculate the remaining path to the target.
*
* @param grid The full grid.
* @param x The current X coordinate.
* @param y The current Y coordinate.
* @param solution The current solution matrix.
* @param path The path we took to get from the source cell to the current location.
* @returns {string|boolean} Either the path to the target cell or false.
*/
function getPathPart(grid, x, y, solution, path) {
const n = grid.length
// are we there yet?
if (x === n - 1 && y === n - 1 && grid[y][x] === 1) {
solution[y][x] = 1
return path
}
// did we step on a 0 cell or outside the grid?
if (!isSafe(grid, x, y)) return false
// are we walking onto an already-marked solution coordinate?
if (solution[y][x] === 1) return false
// none of the above? let's dig deeper!
// mark the current coordinates on the solution matrix
solution[y][x] = 1
// attempt to move right
const right = getPathPart(grid, x + 1, y, solution, path + 'R')
if (right) return right
// right didn't work: attempt to move down
const down = getPathPart(grid, x, y + 1, solution, path + 'D')
if (down) return down
// down didn't work: attempt to move up
const up = getPathPart(grid, x, y - 1, solution, path + 'U')
if (up) return up
// up didn't work: attempt to move left
const left = getPathPart(grid, x - 1, y, solution, path + 'L')
if (left) return left
// no direction was successful: remove this cell from the solution matrix and backtrack
solution[y][x] = 0
return false
}
function getPath(grid) {
// grid dimensions
const n = grid.length
// prepare solution matrix
const solution = []
for (let i = 0; i < n; i++) {
const row = Array(n)
row.fill(0)
solution[i] = row
}
return getPathPart(grid, 0, 0, solution, '')
}
/**
* Creates an instance of the "rat in a maze" based on a given grid (maze).
*/
export class RatInAMaze {
constructor(grid) {
// first, let's do some error checking on the input
validateGrid(grid)
// attempt to solve the maze now - all public methods only query the result state later
const solution = getPath(grid)
if (solution !== false) {
this.path = solution
this.solved = true
} else {
this.path = ''
this.solved = false
}
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
javascript-Backtracking.rar
共18个文件
js:18个
需积分: 1 0 下载量 87 浏览量
2024-09-15
09:51:23
上传
评论
收藏 10KB RAR 举报
温馨提示
javascript-Backtracking.rar
资源推荐
资源详情
资源评论
收起资源包目录
Backtracking.rar (18个子文件)
Backtracking
MColoringProblem.js 1KB
SumOfSubset.js 2KB
generateParentheses.js 810B
AllCombinationsOfSizeK.js 683B
tests
SumOfSubset.test.js 402B
AllCombinationsOfSizeK.test.js 539B
NQueens.test.js 555B
Sudoku.test.js 1KB
RatInAMaze.test.js 3KB
MColoringProblem.test.js 514B
KnightTour.test.js 760B
GeneratePermutations.test.js 1KB
GenerateParentheses.test.js 246B
GeneratePermutations.js 851B
KnightTour.js 2KB
RatInAMaze.js 4KB
Sudoku.js 2KB
NQueens.js 1KB
共 18 条
- 1
资源评论
蜡笔小流
- 粉丝: 2393
- 资源: 1242
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功