【LeetCode】419. Battleships in a Board

来源:互联网 发布:北京现代软件学院骗局 编辑:程序博客网 时间:2024/06/15 09:32


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:

X..X...X...X
In the above board there are 2 battleships.

Invalid Example:

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

Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?


给定一个数组,X表示船 .表示空,求一共有多少条船。

其中:如果一个X的纵向或者横向上有X,则这俩是一条船。以此类推。

这道题有个附属条件是只用复杂度为 O(1)的额外内存并且不能修改入参。


思路:一个X的左边或者上面如果没有X,则船数+1;


/** * @param {character[][]} board * @return {number} */var countBattleships = function(board) {    var count = 0;    for(var i=0;i<board.length;i++){        for(var j=0;j<board[i].length;j++){            if(i>0&&j>0){                if(board[i-1][j]==='.'&&board[i][j-1]==='.'&&board[i][j]==="X"){                    count++;                }            }else if(i>0&&j===0){                if(board[i-1][j]==='.'&&board[i][j]==="X"){                    count++;                }            }else if(j>0&&i===0){                if(board[i][j-1]==='.'&&board[i][j]==="X"){                    count++;                }            }else{                //(i===0&&j===0)===true                if(board[i][j]==="X"){                    count++;                }            }                    }    }    return count;};










原创粉丝点击