Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
You receive a valid board, made of only battleships or empty slots.Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X'表示,空位用 '.'表示。 你需要遵守以下规则:
给你一个有效的甲板,仅由战舰或者空位组成。战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1 (N 行, 1 列)组成,其中N可以是任意大小。两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。
我按行优先和列优先把每个战舰都算两遍,最后除以2即可。但对于长条形的战舰,如横向长条,则首次搜索到+1,连续搜索-1,以抵消纵向遍历时算多的次数。
两组双层的for循环仅仅是改变行列循环次序。所以是复制粘贴稍微改下就能解决的事情。
还有一种解法也是同样复杂度的,仅当该节点是'X'且其左边和上边不是'X'或越界则ans++,即只算每搜战舰的左上角,其实这种解法更容易理解,只是我一开始就想成这样了。
解释可能不是很完善,以后再写,