在一维网格数组中查找组

时间:2016-06-19 17:34:40

标签: algorithm flood-fill linden-scripting-language

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

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

1 个答案:

答案 0 :(得分:0)

这是一个带注释的参数化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);
}