You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现checkMatching函数的循环调用直至无数组返回?

解决递归遍历所有匹配项的问题

看起来你需要实现一个**广度优先搜索(BFS)**的逻辑,来遍历所有层级的相邻匹配位置,直到没有新的匹配项产生为止。你当前的代码只处理了初始调用和一次浅层遍历,我们可以通过while循环结合队列的方式,实现完整的遍历逻辑,同时高效避免重复项。

问题分析

你现有代码的核心问题:

  • 仅手动处理了两层调用(初始调用 + 一次map内的调用),无法自动遍历到所有层级的匹配
  • map内部调用checkMatching时,错误传入了初始的param2和param3,而不是当前遍历项的row和column
  • 去重逻辑使用findIndex,时间复杂度较高,适合用集合来快速判断是否已访问

解决方案:BFS遍历 + 已访问集合

我们可以用队列来保存待处理的位置,每次取出队列中的元素,获取它的相邻匹配,将未处理过的位置加入队列和结果数组,直到队列为空。这样就能覆盖所有层级的匹配:

const checkMatching = (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 };
  
  const directionsWithMatches = [top, bottom, left, right]
    .filter(dir => dir instanceof Object)
    .filter(({ row, column }) => board[row][column].word === board[r][c].word);
    
  return directionsWithMatches;
};

// 初始化变量
const initialMatches = checkMatching(param1, param2, param3);
const allMatchingWords = [...initialMatches];
// 用集合存储已访问的位置,格式为"row-column",方便快速判断
const visited = new Set(initialMatches.map(item => `${item.row}-${item.column}`));
// 队列保存待处理的位置
const queue = [...initialMatches];

// 开始循环遍历,直到队列为空
while (queue.length > 0) {
  // 取出队首的位置
  const current = queue.shift();
  // 获取当前位置的相邻匹配
  const nextMatches = checkMatching(param1, current.row, current.column);
  
  // 遍历每个匹配项
  nextMatches.forEach(match => {
    const key = `${match.row}-${match.column}`;
    // 如果未访问过,就加入结果、队列,并标记为已访问
    if (!visited.has(key)) {
      visited.add(key);
      allMatchingWords.push(match);
      queue.push(match);
    }
  });
}

// 此时allMatchingWords已经包含所有层级的匹配项,且无重复

代码说明

  1. 队列(Queue):用来保存需要处理的位置,确保每个位置的相邻匹配都会被处理
  2. 已访问集合(Visited Set):用字符串格式的row-column作为键,快速判断某个位置是否已经被处理过,避免重复加入结果和队列
  3. 循环逻辑:只要队列不为空,就取出队首元素,获取它的相邻匹配,处理未访问过的项,直到没有新的匹配项可以加入队列

这种方式不仅能自动遍历所有层级的匹配,而且去重逻辑的时间复杂度从O(n²)降到了O(n),效率更高。

内容的提问来源于stack exchange,提问作者peon123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:47:58