Flood fill recursive algorithm

后端 未结 3 1294
一向
一向 2021-01-05 08:14

I\'m trying to make an algorithm that could fill an int array in c#. Basically, as the fill tool in MS Paint, I have a color and if I choose (x,y) coordinates in the array,

3条回答
  •  天命终不由人
    2021-01-05 08:52

    As it was suggested already, the issue is with the number of recursive calls. On a 32bit machine you have 4bytes for the pointers, so if you have a 512*512 image and you want to fill the whole thing, the function pointers alone will occupy 512*512*4bytes = 1MB memory on your stack. And that is the default size of the stack. Regardless of the function pointers, you have another 5 references you pass (array, x, y, initialInt, newInt) which all are copied with every call as temporary objects, and are on the stack until the function call terminates. On the same sized image, those are another 512*512*5*4bytes = 5MB of memory.

    To solve your issue you can modify (same link as above) the size of the stack.

    Also, to save some stack space, you might consider wrapping the parameters inside a single object, in this case you will have only 4bits of temporary memory per call, instead of 20.

    Still, as it was as well pointed out, the best solution is to rewrite your algorithm iteratively.

提交回复
热议问题