gpt4 book ai didi

javascript - 递归问题。如何解决这个问题?

转载 作者:行者123 更新时间:2023-11-29 20:26:55 25 4
gpt4 key购买 nike

我的递归有点问题。我有一个检查点击框的匹配方向的功能

const checkMatchingDirections = (board, r, c) => {
const top = board[r - 1] !== undefined && { row: r - 1, column: c };
const bottom = board[r + 1] !== undefined && { row: r + 1, column: c };
const left = board[r][c - 1] !== undefined && { row: r, column: c - 1 };
const right = board[r][c + 1] !== undefined && { row: r, column: c + 1 };

// filter for edge blocks and finding match color
const directionsWithMatches = [top, bottom, left, right]
.filter(dir => dir instanceof Object)
.filter(({ row, column }) => board[row][column].color === board[r][c].color);

return directionsWithMatches;
};

该函数返回点击框匹配颜色的数组。

我的问题是我想根据该函数先前返回的数组的结果调用该函数 checkMatchingDirections。

其实我是这样创作的

  const matches = checkMatchingDirections(blocks, y, x);

matches.map(({ row, column }) => {
const restMatches = checkMatchingDirections(blocks, row, column);
allMatchingBlocks = [...matches, ...allMatchingBlocks, ...restMatches];
});

但是通过在第一次调用中映射 checkMatchingDirection 的结果来硬编码调用该函数两次。

如何创建调用 checkMathingDirection 结果数组上的 checkMatchingDirection 的函数?

例如。

如果我点击了一个绿色框,然后左侧有 4 个框,顶部有 1 个。都选好了。

最佳答案

洪水填充将像这样工作(伪代码):

  • 创建一个名为“visited”的空位置 map 。
  • 用起始 y,x 调用递归函数“floodfill”。
  • 在“floodfill”中,使用“已访问”- map 检查该位置是否已被访问过。如果"is",则返回,如果“否”,则执行以下操作:
  • 在“已访问” map 中将位置标记为已访问。对所有未定义的邻居执行“floodfill”的递归调用。
  • 最终在“已访问”- map 中获得可到达位置的列表。

关于javascript - 递归问题。如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59136446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com