Efficient Cartesian Product algorithm

后端 未结 6 1695
太阳男子
太阳男子 2020-11-29 07:00

Can somebody please demonstrate for me a more efficient Cartesian product algorithm than the one I am using currently (assuming there is one). I\'ve looked around SO and go

6条回答
  •  半阙折子戏
    2020-11-29 07:32

    The complexity of cartesian product is O(n2), there is no shortcut.

    In specific cases, the order you iterate your two axis is important. For example, if your code is visiting every slot in an array — or every pixel in an in image — then you should try to visit the slots in natural order. An image is typically laid out in ‘scanlines’, so the pixels on any Y are adjacent. Therefore, you should iterate over the Y on the outer loop and the X on the inner.

    Whether you need the cartesian product or wherther is a more efficient algorithm depends on the problem you are solving.

提交回复
热议问题