简体   繁体   English

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

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

I have a little problem with my recursion.我的递归有点问题。 I have a function with checking matching directions of clicked box我有一个检查点击框匹配方向的功能

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;
}; 

That function returns array of matching color of clicked box.该函数返回点击框匹配颜色的数组。

My problem is that I want to recall that function checkMatchingDirections on results of previous returned array from that function.我的问题是我想在该函数之前返回的数组的结果上调用该函数 checkMatchingDirections 。

Actually I'm creating like this其实我是这样创造的

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

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

But's it's hardcoded to recall that function twice by maping results of checkMatchingDirection in first call.但是通过在第一次调用中映射 checkMatchingDirection 的结果来两次调用该函数是硬编码的。

How to create function which gonna recall checkMatchingDirection on results array of checkMathingDirection?如何在checkMathingDirection的结果数组上创建调用checkMatchingDirection的函数?

For example.例如。

If I have clicked one green box and then there's 4 box on the left and one on top.如果我点击了一个绿色框,然后左边有 4 个框,顶部有一个框。 There's all selected.都选好了

A flood fill would work like this (pseudocode):洪水填充将像这样工作(伪代码):

  • create an empty map of locations named "visited".创建一个名为“visited”的空的位置地图。
  • call the recursive function "floodfill" with the starting y,x.使用起始 y,x 调用递归函数“floodfill”。
  • in "floodfill", check whether the location has been visited already using the "visited" - map.在“floodfill”中,使用“visited” - 地图检查该位置是否已经被访问过。 If "yes", then return, else if "no" do the following:如果“是”,则返回,否则如果“否”,请执行以下操作:
  • mark the location as visited in the "visited" - map.在“已访问”地图中将位置标记为已访问。 Do recursive calls of "floodfill" with all the neighbors that are not undefined.对所有未定义的邻居进行“floodfill”的递归调用。
  • finally have a list of reachable locations in "visited" - map.终于在“已访问”中列出了可到达的位置 - 地图。

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

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