栅格的递归算法或填充算法?

时间:2016-12-16 11:42:22

标签: r algorithm recursion flood-fill

我有这样的二进制光栅:

101101
010111
101011
111101

现在我需要逐行执行此操作: 遍历行并计算相邻的单元格(仅为行中的单元格!)。我想得到一个矢量或类似的东西。 例如,对于上面的栅格,它将是:

1st row: 1 2 1

2nd row: 1 3

3rd row: 1 1 2

4th row: 4 1

我读了很多关于洪水填充算法等等。但我不能做对。

我尝试了这种递归算法:

rec=function(x)
   {if (x==0)
       {return 0)
    else return(1+rec(x+1))}

但它没有用。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用rle

xy <- read.table(text = "1 0 1 1 0 1
0 1 0 1 1 1
1 0 1 0 1 1
1 1 1 1 0 1", sep = "")
xy

apply(xy, MARGIN = 1, FUN = function(x) {
  x <- rle(x)
  x$lengths[x$values == 1]
})

[[1]]
V2 V5    
 1  2  1 

[[2]]
V3    
 1  3 

[[3]]
V2 V4    
 1  1  2 

[[4]]
V5    
 4  1

答案 1 :(得分:0)

根本不需要填充算法。也不需要递归。

只计算非零值。最简单的状态机:

Starting state in the beginning of every line is 0
When state is 0 and you meet 1, remember X-position Start and make state 1
When state is 1 and you meet 0, make state 0 and add `Current - Start` to list
In other cases do nothing