can counting contiguous regions in a bitmap be improved over O(r * c)?

前端 未结 5 1104
南笙
南笙 2021-02-15 16:52

You are given an image of a surface photographed by a satellite.The image is a bitmap where water is marked by \'.\' and land is marked by \'*\'. Adjacent group of

5条回答
  •  余生分开走
    2021-02-15 17:22

    Asymptotically your approach is the best O(n).

    However, I noticed a couple of things:

    First:

    inside the function markVisited you check a cells neighbors in the order:

    down, right, up, left, down-right, up-left, up-right, down-left
    

    A better order would be:

    left, right, up-left, up, up-right, down-left, down, down-right
    

    This will play nicer in the cache since it is starting by reading values directly next to the current position, and sequentially in a given row.

    (note that starting with the diagonals would mark visited to a larger number of locations, but since checking if a cell was visited is only the last check it wouldn't save any time).

    Secondly:

    In the worst case of a satellite image that contains only land, your algorithm will visit each cell multiple times, (something like once for each neighbor the cell has).

    This means you are approximately doing eight times more array accesses than possibly needed.

    I believe that you can solve this problem with a more or less linear pass over the data.

    I'm currently thinking of an approach, if it works I'll add the code as an edit.

提交回复
热议问题