簡體   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