好的,这个问题的表述有点奇怪,但我希望这能给您澄清事情。
我有一个示例2D数组。
$array = array(
array(1, 0, 0, 0, 1, 0, 0, 1),
array(0, 0, 1, 1, 1, 1, 0, 1),
array(0, 1, 1, 0, 1, 0, 0, 0),
array(0, 1, 1, 0, 0, 0, 1, 0),
array(1, 0, 0, 0, 1, 1, 1, 1),
array(0, 1, 1, 0, 1, 0, 1, 0),
array(0, 0, 0, 0, 0, 0, 0, 1)
);
当按行迭代(并以 \n 结束每一行),然后对每一行进行按列迭代时,它会输出类似于以下内容:(░░=0,▓▓=1)
▓▓░░░░░░▓▓░░░░▓▓
░░░░▓▓▓▓▓▓▓▓░░▓▓
░░▓▓▓▓░░▓▓░░░░░░
░░▓▓▓▓░░░░░░▓▓░░
▓▓░░░░░░▓▓▓▓▓▓▓▓
░░▓▓▓▓░░▓▓░░▓▓░░
░░░░░░░░░░░░░░▓▓
但是我想做的是“分析”数组,只保留一个连续的形状(具有最多“单元格”),在这个例子中,结果将是:
░░░░░░░░▓▓░░░░░░
░░░░▓▓▓▓▓▓▓▓░░░░
░░▓▓▓▓░░▓▓░░░░░░
░░▓▓▓▓░░░░░░░░░░
▓▓░░░░░░░░░░░░░░
░░▓▓▓▓░░░░░░░░░░
░░░░░░░░░░░░░░░░
我的初始方法是:
Assign each ▓▓ cell a unique number (be it completely random, or the current iteration number):
01 02 03 04050607 08 0910 11 1213 14 15 16171819 2021 22 23 24
Iterate through the array many, MANY times: every iteration, each ▓▓ cell assumes the largest unique number among his neighbours. The loop would go on indefinitely until there's no change detected between the current state and the previous state. After the last iteration, the result would be this:
01 21 08 21212121 08 2121 21 2121 24 21 24242424 2121 24 24 24
Now it all comes down to counting the value that occurs the most. Then, iterating once again, to turn all the cells whose value is not the most popular one, to 0, giving me the desired result.
额外加分:将所有blob分成一个2D数组的数组,按单元格数排序,以便我们也可以处理最小的blob。