繁体   English   中英

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

[英]Problem with recursion. How to solve that problem?

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

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 个框,顶部有一个框。 都选好了

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM