我正在获得NxM板的输入,该板看起来像是战舰游戏的板。 “#”代表战列舰,“-”代表空白。船没有彼此相邻放置,也不是对角放置。 (在两艘船之间必须为“-”)。 我需要计算一下船上有多少艘船。
我知道当船的尺寸为1x1时如何计数。
subnum=0
for i in range(len(board[1:-2])):
for j in range(len(board[1:-2])):
if board[i][j] == "#":
if board[i+1][j] == "-" and board[i-1][j]=="-" and board[i][j+1]=="-" and board[i][j-1]=="-":
subnum += 1
答案 0 :(得分:0)
如果船只不是水平排列且彼此不相邻,则可以只使用代码,而仅测试“#”上方的字段是否为“-”(或者如果船只触及木板边界,则为空)。算一下。
--#------
--#--#---
--#--#---
-----#---
在此示例中,它将计为2,因为只有2个“#”在其上方没有其他“#”。在您的示例中,我也并没有真正获得for循环(它们都是相同的,但是您编写的板是NxM)。我建议像这样:
subnum=0
for x in range(len(board)):
for y in range(len(board[x])):
if board[x][y] == "#" and (y == 0 or board[x][y-1] == "-"):
subnum += 1
我在这里使用x,y来澄清“木板”的外观(x->水平,y->垂直)。如果“面板”看起来不同,则可能需要更改它。
此代码将适用于所有水平和垂直放置的船舶:
def check(board):
visited = set()
subnum = 0
for x in range(len(board)):
for y in range(len(board[x])):
if not (x,y) in visited: #we havn't looked at this field already
if board[x][y] == '#': #a ship!
subnum += 1
if x < len(board) - 1: #need to test if ship expands to the right
for x1 in range(x+1, len(board)):
if board[x1][y] == '#':
visited.add((x1,y)) #avoid this field later, because it belongs to the already counted ship
else:
break #end of ship reached
if y < len(board[x]) - 1: #need to test if ship expands to the bottom
for y1 in range(y+1, len(board[x])):
if board[x][y1] == '#':
visited.add((x,y1)) #avoid this field later, because it belongs to the already counted ship
else:
break #end of ship reached
return subnum
好的,第三种方法,没有设置,甚至更容易:
def check2(board):
subnum = 0
for x in range(len(board)):
for y in range(len(board[x])):
if board[x][y] == '#': #a ship!
if (x == 0 or board[x-1][y] != '#') and (y == 0 or board[x][y-1] != '#'):
subnum += 1
return subnum
给予:
>>> board = [ '#-#-#######-###---#' ]
>>> check2(board)
5
>>> board = [ '#-#-#######-###---#', '#---------------#-#' ]
>>> check2( board )
6
答案 1 :(得分:0)
根据我上面的评论中的想法,这是一个更简单的版本。
def check(board):
subnum = 0
for i in range(len(board)):
for j in range(len(board[i])):
if (
board[i][j] == "#"
and (i == 0 or board[i-1][j] == "-")
and (j == 0 or board[i][j-1] == "-")
):
subnum += 1
return subnum
答案 2 :(得分:-2)
from numpy import *
from array import * #imports
board=array([#,-,-,-][-,-,#,-][#,-,-,-][-,-,-,#]) #your board data
array('u',board.flatten()).count('#') #display count of bartterships