D
D
Danil Antoshkin2015-07-10 12:46:10
Java
Danil Antoshkin, 2015-07-10 12:46:10

How to implement the algorithm for placing ships on the field?

Good afternoon, I want to know how to write an algorithm for arranging ships so that they do not touch each other?
A 10x10 field is a 2D array of symbols
. Ships from normal naval combat:
4 cells
3 cells
2 cells
1 cell

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Litvinenko, 2015-07-10
@edli007

Need random generation?
1. Randomly determine the position of the ship
2. Exclude occupied cells from the array, if there is no space and there are ships, you reset the field.
3. go to point 1 until you place all the ships.

S
Saboteur, 2015-07-10
@saboteur_kiev

Some too general question. Do you not understand how to check for neighboring empty cells in a two-dimensional array?
Create a function where you do this in a loop or with separate checks:
if (myarray[x+1,y]==1)
{
return false;
}
and check for all required sizes. You can cut it down a bit here.

S
Sumor, 2015-07-10
@Sumor

The most important thing is that in a classic naval battle, if you place ships starting with a 4-deck, then two 3-deck, then three 2-deck and four single-deck, then there is always an arrangement of ships. This is easily proven. If you start with single-deck, you can get into a mess.
The four-deck is placed by choosing the direction - horizontal / vertical and choosing the initial cell - a total of 140 options.
You mark the occupied cells, the cells around the ship and proceed to the three-deck ones.
You run through unoccupied cells and try to check the possibility of placing the ship horizontally or vertically. Store all possible options in an array, and then choose one randomly.
Repeat until all ships are placed. Proof-of-Existence Deployment ensures that you always have a place to place your ship.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question