返回
如何从二维数组中提取遵循规则的路径?
javascript
2024-03-23 08:26:27
从二维数组中提取遵循规则的路径
问题
想象你面对一个二维数组,上面布满了字母和符号。你的任务是从这个数组中提取一条路径,这条路径必须满足特定的规则:
- 仅包含大写字母
- 转弯点只能是字母或“+”
路径规则
这条路径必须遵循以下规则:
- 从“>”开始。
- 遇到字母时,将其添加到路径中。
- 遇到“+”时,根据相邻字符来改变方向:
- 如果下一个字符是“|”,则向左或向右转弯。
- 如果下一个字符是“-”,则向上或向下转弯。
- 继续移动,直到遇到“s”。
- 最后将“s”添加到路径中。
代码实现
为了提取符合这些规则的路径,你可以使用以下 JavaScript 代码:
function generatePath(grid) {
let path = '';
let currentIndex = findStartingIndex(grid);
let currentRow = Math.floor(currentIndex / grid[0].length);
let currentCol = currentIndex % grid[0].length;
const offsets = [[-1, 0], [1, 0], [0, -1], [0, 1]];
let direction = 3; // Start with right direction
while (grid[currentRow][currentCol] !== 's') {
const currentChar = grid[currentRow][currentCol];
if (currentChar !== ' ' && currentChar !== '|') {
path += currentChar;
}
if (currentChar === '+') {
const nextRow = currentRow + offsets[direction][0];
const nextCol = currentCol + offsets[direction][1];
if (nextRow >= 0 && nextRow < grid.length && nextCol >= 0 && nextCol < grid[0].length) {
const nextChar = grid[nextRow][nextCol];
if (nextChar === '-') {
direction = direction % 2 === 0 ? 2 : 0; // Change to left or right
} else {
direction = direction % 2 === 0 ? 3 : 1; // Change to up or down
}
}
}
currentRow += offsets[direction][0];
currentCol += offsets[direction][1];
}
path += 's';
return path;
}
function findStartingIndex(grid) {
for (let i = 0; i < grid.length; i++) {
const row = grid[i];
const index = row.findIndex(char => char === '>');
if (index !== -1) {
return index + i * row.length;
}
}
}
使用方法
- 定义一个二维数组
grid
,其中包含字母和符号。 - 调用
generatePath(grid)
函数,它将返回遵循指定规则的路径。 - 访问
path
变量以获取路径字符串。
示例
下面是一个示例,展示了如何使用此代码:
const grid = [
['>', '-', '-', '-', 'A', '-', '@', '-', '+'],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|'],
['+', '-', 'U', '-', '+', ' ', ' ', ' ', 'C'],
['|', ' ', ' ', ' ', '|', ' ', ' ', ' ', '|'],
['s', ' ', ' ', ' ', 'C', '-', '-', '-', '+'],
];
const path = generatePath(grid);
console.log('Path:', path); // Output: >---A-@-+|C|+---C|+-U-+|s
此代码生成了一条符合指定规则的路径:>---A-@-+|C|+---C|+-U-+|s
。
常见问题解答
1. 为什么要遵循这些规则提取路径?
这些规则可能代表了一个特定问题的解决过程,例如在一个迷宫中找到出口。它们提供了从数组中提取有意义信息的框架。
2. 除了给出的规则,还有其他约束吗?
否,给出的规则涵盖了所有必要的约束,以提取符合预期模式的路径。
3. 如何处理数组边界?
在给定的代码中,我们假设数组边界已得到适当处理。如果存在超出数组范围的尝试,需要根据具体情况添加额外的检查。
4. 这种方法是否可以在具有不同尺寸和形状的数组上使用?
是的,只要数组包含遵循给定规则的路径,这种方法可以用于任何尺寸或形状的数组。
5. 是否可以自定义路径规则?
是的,你可以根据需要修改代码中的规则,以提取符合自定义条件的路径。