Remix.run Logo
▲ hatthew 3 hours ago

What's the utility of this? It's arguably still using a stack, just encoded in the original data structure itself. If your original data structure somehow uses colors but is also fine with the algorithm overwriting with its own colors, I guess it works? But those are very unusual preconditions. For any real world scenario I can imagine, I feel like there's a better solution.

If the colors in your original data are important, then you can't really just overwrite them and/or assume that the algorithm can use its own colors. You're going to have to add a stack.

If your original data doesn't have colors, adding a stack is better than integrating metadata into the original data structure.

If for some reason your original data has colors but they aren't considered important, then just remove the colors and add a stack.

If your concern is about dynamic memory, preallocate static memory equal to the size of the original data structure.

▲Jtsummers 3 hours ago | parent [-]

> What's the utility of this?

Constant memory usage. It uses a small amount of additional memory (tracking the current pixel, pixel value, and a couple temp variables used for calculations) over the image itself making it a very low overhead algorithm. You can basically get away with 5 more variables, 20 more bytes if they're all 4-byte values, using this approach compared to the much greater memory needs of a stack-based approach (either a stack data structure or recursive). And actually just 4 variables since the D and P variables don't overlap in lifetime.

EDIT: Light editing of the above for grammar and clarity.