简体   繁体   中英

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.

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.

How to create function which gonna recall checkMatchingDirection on results array of checkMathingDirection?

For example.

If I have clicked one green box and then there's 4 box on the left and one on top. There's all selected.

A flood fill would work like this (pseudocode):

  • create an empty map of locations named "visited".
  • call the recursive function "floodfill" with the starting y,x.
  • in "floodfill", check whether the location has been visited already using the "visited" - map. 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.
  • finally have a list of reachable locations in "visited" - map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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