我正在尝试验证 战舰 场地,并使用以下规则:
- 战舰不会接触到边缘或角落;
- 战舰是直的;
- 有1艘4格的战舰、2艘3格的战舰、3艘2格的战舰和4艘1格的战舰。
场地表示为 byte[10][10]
数组。我能用什么算法来实现这个功能?我使用的语言是Java,但任何语言都可以。
我正在尝试验证 战舰 场地,并使用以下规则:
场地表示为 byte[10][10]
数组。我能用什么算法来实现这个功能?我使用的语言是Java,但任何语言都可以。
修正为使用正确的船只规格。
伪代码:
initialise the ship map with pairs of (size, amount of ships) values
initialise your map[12][12]:
for every place at row and column coordinate of 0 or 11 (the border)
mark it as visited
for every other place
mark it as not visited
fill it with either ship or ocean tile from your input
for each row from 1 to 10
for each column from 1 to 10
if that place has not been visited yet
mark that place as visited
if that place is a ship tile
check the places to the "right" (bigger column numbers)
... and bottom (bigger "row" numbers)
until you hit a visited or ocean tile
the amount of ship tiles checked (including the first) is current ship's length
decrease the amount of ships of that length in the ship map by one
mark all ship tiles of the current ship as visited
mark all tiles surrounding those ship tiles as visited
if the ship map includes any pairs with non-zero (including negative) amount of ships
the map is invalid
else
the map is valid
检查所有围绕找到的船块的瓷砖是否为空
(+1) - Thomas简单算法。主要思路:每个“满”场必须被分配给某艘船。
我不太明白你需要什么: 但我认为战舰游戏中的船只应该具有基本结构:
Ship{
//x, y: top, left of ship's position
int: x;
int: y;
int: size;//[1,2,3,4]
boolean: isHorizontal;//It means a ship is vertical or horizontal on the map.
}
如果您将所有船只声明为数组,例如:Ship[SHIP_NUMBER]: arrShip
我可以向您展示其中之一:
2层甲板船-水平
:shipmap [0] [0] = 1
,map [0] [1] = 1
。因此,您不能将船只设置在已占用的单元格上。ship.x < 0 || ship.y < 0 || ship.x > 9 || ship.y > 9
由于您最多有10艘船,且数据结构是一个byte
数组,为什么不使用值0表示水域,使用值1到10表示船只领域。
然后,您可以迭代字段并检查周围的字段(可以根据迭代方向进行优化,以避免重复检查相同的组合)。
如果遇到值为0,则继续。
如果获得值> 0,则检查周围的字段是否包含除0和该字段值之外的值(检测接触的船只)。
此外,如果周围的字段包含相同的值,但在角落处接触,则说明发现了非法设置。 L形船只也应违反非对角线规则。
最后要检查的是船只是否可能包含孔洞。在这种情况下,只需存储您找到的每艘船的一系列字段,并检查新检查的字段是否紧邻该范围。这也将为您提供船只数量,因为您可以在最后查询每艘船的范围长度。
考虑以下部分板:
A B C D E F G H I J
_____________________
1 | 0 0 2 0 0 0 0 0 0 0
2 | 0 1 0 0 3 3 0 4 0 4
3 | 0 0 0 0 0 3 0 0 0 0
我认为使用更好的数据结构来表示棋盘位置将大大简化项目。您可以定义一个Ship
类型,其中包含三个字段:船的长度、船的方向和(根据方向)其最上方或最左侧的方块。您将所有想要的船存储在列表中(它将有10个条目)。您通过移动列表来验证您的位置,标记船的所有方块为占用,并将所有相邻的方块标记为禁止。如果在放置船时,您必须将船放置在已占用或禁止的方块中,则知道您有一个无效的位置。另一方面,如果您能够放置所有船而没有冲突,那么您就知道构造正确的棋盘位置。
这样做的额外优点是允许您一次放置一艘船,并立即报告无效配置,这意味着几乎不需要更改与玩家放置船只的用户界面配合工作。