LeetCode – 419. Battleships in a Board

題目來源:LeetCode -419. Battleships in a Board


題目:

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.

Example:

In the above board there are 2 battleships.

Invalid Example:

This is an invalid board that you will not receive – as battleships will always have a cell separating between them.

粗略翻譯:

題目會給予一個二維陣列(2D Board),要計算這二維陣列中的戰艦有幾艘

其中’X’代表戰艦;’.’代表空白區域

題目明文規定程式只會收到有效的二維陣列,

戰艦呈現的方式只會是水平或垂直

戰艦長度可能會是1xN (1 列, N 行) or Nx1 (N 列, 1 行),N可能會是任何大小.

兩艘戰艦之間一定會有空白區域 ‘. ‘做為間隔,不會有緊鄰的兩艘戰艦在一起

 

解法:

跑雙層迴圈,r代表Row,c代表Column,

每次在檢查值時,先判斷該位置是不是’X’,如果是則依序檢查r-1跟c-1的值是不是’.’

如果r-1或c-1其中一個值為’X’,代表這仍是同一艘戰艦,

為了不重複計算戰艦數量,因此不能加進戰艦數量裡

如果條件都成立,則戰艦數量+1

 


網站:http://wp.mlab.tw/
GitHub:https://github.com/yoll522/LeetCode
程式碼:https://github.com/yoll522/LeetCode/tree/master/419.%20Battleships%20in%20a%20Board

Leave a Reply

你的電子郵件位址並不會被公開。 必要欄位標記為 *