在一维网格数组中查找组

Finding groups in a single-dimensional grid array

如果我有一个随机生成的数组,其中包含 60 项 (表示为 6x10) 6 种类型 (表示为整数 0-5), 如何在数组中搜索相同类型的组? (Vertically/horizontally 个至少有 3 个的连接组。)

我在类似于 C++ 和 C 的脚本环境 (LSL) 中工作。

这是一个带注释的参数化 working javascript 示例,诀窍是使用数组来表示您已经访问过的单元格/节点。

var arr = [], visited, grp, val, rowLength = 6, threshold = 3;

// generate random array
for (var i = 0; i < 60; i++) {
  arr.push(Math.floor(Math.random() * 6));
}

alert(JSON.stringify(findGroups())); // executing the function and displaying the result.

function findGroups() {
  visited = []; // resetting visited
  var ret = []; // the return value is an array of groups
  for (var i = 0; i < arr.length; i++) {
    if (!visited[i]) {
      val = arr[i]; // set the value we are currently inspecting
      grp = []; // reset the current group
      flood(i); // the recursive flood function
      if (grp.length >= threshold) // add the group to the result if it meets the criteria 
        ret.push(grp);
    }
  }
  return ret;
}

function flood(idx) {
  if (visited[idx] || arr[idx] != val) // only look at cells with matching value...  
    return; // ... that weren't visited yet
  visited[idx] = true; // mark as visited
  grp.push(idx); // add index to current group
  if (idx % rowLength != 0) // can go left
    flood(idx - 1);
  if (idx % rowLength != rowLength - 1) // can go right
    flood(idx + 1);
  if (idx >= rowLength) // can go up
    flood(idx - rowLength);
  if (idx < arr.length - rowLength) // can go down
    flood(idx + rowLength);
}