Programming Contest Question: Counting Polyominos

后端 未结 7 618
醉酒成梦
醉酒成梦 2020-12-15 11:33

Please see my own answer, I think I did it!


Hi,

An example question for a programming contest was to write a program that finds out ho

7条回答
  •  有刺的猬
    2020-12-15 12:22

    Just solved this as well in java. Since all here appear to have performance issues. I give you mine as well.

    Board reprsentation:

    2 arrays of integers. 1 for the rows and 1 for the columns.

    • Rotation: column[i]=row[size-(i+1)], row[i] = reverse(column[i]) where reverse is the bits reversed according to the size (for size = 4 and first 2 bits are taken: rev(1100) = 0011)
    • Shifting block: row[i-1] = row[i], col[i]<<=1
    • Check if bit is set: (row[r] & (1< 0
    • Board uniqueness: The board is unique when the array row is unique.
    • Board hash: Hashcode of the array row
    • ..

    So this makes all operations fast. Many of them would have been O(size²) in the 2D array representation instead of now O(size).

    Algorithm:

    • Start with the block of size 1
    • For each size start from the blocks with 1 stone less.
    • If it's possible to add the stone. Check if it was already added to the set.
    • If it's not yet added. Add it to the solution of this size.
      • add the block to the set and all its rotations. (3 rotations, 4 in total)
      • Important, after each rotation shift the block as left/top as possible.
    • +Special cases: do the same logic for the next 2 cases
      • shift block one to the right and add stone in first column
      • shift block one to the bottom and add stone in first row

    Performance:

    • N=5 , time: 3ms
    • N=10, time: 58ms
    • N=11, time: 166ms
    • N=12, time: 538ms
    • N=13, time: 2893ms
    • N=14, time:17266ms
    • N=15, NA (out of heapspace)

    Code: https://github.com/Samjayyy/logicpuzzles/tree/master/polyominos

提交回复
热议问题