Java – how to verify the battleship domain?

I tried to validate the battle ship field with these rules:

>The ship shall not touch the side or corner; > The ship is straight; > Have 1 × 4 deck ship, 2 × 3 deck, 3 × 2 deck, 4 × 1 deck ship

This field is represented as a byte [10] [10] array What algorithm can I use to achieve this goal? The language I use is Java, but any language is very good

Solution

Quick check effectiveness: 1 × 4 deck ship, 4 × 1 deck vessels must occupy 1 * 4 2 * 3 * 2 4 * 1 = 20 units Therefore, if your field does not contain 20 cells, it is invalid (ships overlap or ships are insufficient)

Now you need to verify that the number of ships of each type is correct and that the ships will not touch You can do this through connected component analysis A simple two-way algorithm will be used here (pseudo code and examples in the link) This will give you the size, location, and shape of each blob in the farm

From there, you just iterate over each blob and check whether it is vertical or horizontal This is simple – only the width (the difference between the maximum and minimum column values) and height (the difference between the maximum and minimum row values) of the blob are calculated One of them must be equal to 1 If not, the two ships are in contact and the area is invalid

Finally, check whether the number of each ship type is correct If you do not, the field is invalid If you do, the field is valid and you are done

edit

Ships can also be in end-to-end contact, but this will reduce the total number of ships (increase the number of ships of a certain type) so that the last test cannot be carried out

Edit 2

Correct ship specifications have been used

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>