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

前端 未结 5 1101
南笙
南笙 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:19

    I think the confusion here is that your algorithm does actually run in linear time, not quadratic time.

    When using big-O notation, n stands for the input size. Your input here is not just r or just c, but rather, r * c, as it is a grid of nodes. Your algorithm runs in O(r * c), as you said in your question... thus your algorithm runs in O(n) which is linear time.

    It seems to me that any algorithm that solves this problem will have to read each input cell once in the worst case. Thus the best running time you can hope for is O(n). As your algorithm runs in O(n) you can't have any algorithm that runs of a faster order, in the worst case, than the algorithm you proposed.

    I can think of some clever tricks. For example, if you have a block of *s, you could only check the diagonals, in certain cases. That is, if you have

    ......
    .****.
    .****.
    .****.
    .****.
    ......
    

    it won't matter if you only read these cells:

    ......
    .*.*..
    ..*.*.
    .*.*..
    ..*.*.
    ......
    

    unless for example you have something in the bottom-left-most corner, in which case you would need to read that bottom-left-most *. So maybe in certain cases your algorithm can run more quickly, but for the worst case (which is what O measures), it will have to be O(n).

    EDIT: Also even in that case where you only read half the nodes, the run-time would be O(n/2) which is still of the same order (O(n)).

提交回复
热议问题