[LeetCode] 419. Battleships in a Board

Warships on the plate. Meaning of the questions is to give a two-dimensional array, including the point and X. Judgment has several warships. Is defined ship must be horizontal or straight and optionally at least one cell interval between two ships. The idea is to traverse once input, to find the starting point of warships. The so-called warships starting point is to point X and point above and to the left of the point can not be X. This problem is actually relatively simple, because if the ship can be adjacent to, will be more difficult to judge.

Time O (n ^ 2)

Space O (1)

 1 /**
 2  * @param {character[][]} board
 3  * @return {number}
 4  */
 5 var countBattleships = function(board) {
 6     let m = board.length;
 7     if (m === 0) return 0;
 8     let n = board[0].length;
 9     let res = 0;
10     for (let i = 0; i < m; i++) {
11         for (let j = 0; j < n; j++) {
12             if (board[i][j] === '.') continue;
13             if (i > 0 && board[i - 1][j] === 'X') continue;
14             if (j > 0 && board[i][j - 1] === 'X') continue;
15             res++;
16         }
17     }
18     return res;
19 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/11795980.html