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

时间:2019-12-02 09:59:55

标签: javascript arrays loops recursion

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

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 个答案:

答案 0 :(得分:2)

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

  • 创建一个名为“已访问”的位置的空地图。
  • 以y,x开头调用递归函数“ floodfill”。
  • 在“填充”中,使用“已访问”-地图检查该位置是否已被访问。如果为“是”,则返回,否则为“否”,请执行以下操作:
  • 在“已访问”-地图中标记访问过的位置。对所有未定义的邻居进行“填充”的递归调用。
  • 最终在“已访问”-地图中具有可到达位置的列表。
相关问题