leetcode 419

题目说明:

Given an 2D board, count how many different 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:

...X
XXXX
...X

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

解法1思路:

这里需要计算战舰队的数量count,可转换为计算每个战舰队位于最左上角的船只(我们称为战舰队头)。 用两个循环,对网格内的每一个格子进行遍历,若该格子为X(即有战舰),则分以下几种情况: 
若在网格的最左上角(即i=0,j=0),则存在一个舰队,count自加1; 
若在网格的最上角(即i=0),但不在最左边(即j!=0),则需要判断该位置的左边(即board[i][j-1])是否有战舰存在,若其左边不存在战舰,则该位置为战舰队头,count自加1; 
若在网格的最左边(即j=0),但不在最上边(即i!=0),则需要判断该位置的上面(即board[i-1][j])是否有战舰存在,若其上面不存在战舰,则该位置为战舰队头,count自加1; 
若战舰不在最左边也不在最上边(即i!=0且j!=0),则需要判断该战舰的左边和上面是否还有战舰存在,若其左边和上面都不存在战舰,则该位置为战舰队头,count自加1; 
其余情况,战舰都不属于战舰队头。

解法1代码:

int countBattleships(vector<vector<char>>& board)
{
    int counter = 0;
    for (int i = 0; i < board.size(); i ++) {
        for (int j = 0; j < board[i].size(); j ++) {
            if (board[i][j] == ‘X‘) {
                if (i == 0 && j == 0)
                    counter ++;
                else if (i == 0 && j != 0 && board[i][j - 1] == ‘.‘)
                    counter ++;
                else if (j == 0 && i != 0 && board[i - 1][j] == ‘.‘)
                    counter ++;
                else if (i != 0 && j != 0 && board[i - 1][j] == ‘.‘ && board[i][j - 1] == ‘.‘)
                    counter ++;
            }

        }
    }

    return counter;
}

解法2思路:

和解法1相似,只是这种解法是从反面分析,逐项排除非battleships的项,最后留下符合条件的项,这种剪枝策励在leetcode的算法题中非常常见。

解法2代码:

int countBattleships(vector<vector<char>>& board)
{
    int counter = 0;
    for (int i = 0; i < board.size(); i ++) {
        for (int j = 0; j < board[i].size(); j ++) {
            if (board[i][j] == ‘.‘)
                continue;
            if (j > 0 && board[i][j - 1] == ‘X‘)
                continue;
            if (i > 0 && board[i - 1][j] == ‘X‘)
                continue;

            ++ counter;
        }
    }

    return counter;
}

部分引用自:

http://blog.5ibc.net/p/94878.html

http://blog.csdn.net/mebiuw/article/details/52876700

时间: 2024-08-24 14:55:54

leetcode 419的相关文章

[LeetCode]419 Battleships in a Board(暴力,dfs)

题目链接:https://leetcode.com/problems/battleships-in-a-board/?tab=Description 题意:问平面上有多少条船,船是1*n或者n*1的,并且不相交. 最简单的想法就是直接dfs,但是看到题目里有一个思考,那就是不修改平面并且空间O(1)的one-pass. 这时候就想到应该是遍历所有船的左上角的端点,统计就行了.很简单. 1 public class Solution { 2 public int countBattleships(

LeetCode &quot;419. Battleships in a Board&quot;

The follow-up question is fun: "Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?" When we meet an 'X', we need to check if it is vertical or horizontal: they will never happen at the same ti

[Leetcode][Python]36: Valid Sudoku

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 36: Valid Sudokuhttps://oj.leetcode.com/problems/valid-sudoku/ Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.The Sudoku board could be partially filled, where empty

【LeetCode】未分类(tag里面没有)(共题)

[419]Battleships in a Board (2018年11月25日)(谷歌的题,没分类.) 给了一个二维平面,上面有 X 和 . 两种字符. 一行或者一列连续的 X 代表一个战舰,问图中有多少个战舰.(题目要求one pass, 空间复杂度是常数) 题目说了每两个战舰之间起码有一个 . 作为分隔符,所以不存在正好交叉的情况. 题解:我提交了一个 floodfill 的题解,能过但是显然不满足要求. discuss里面说,我们可以统计战舰的最上方和最左方,从而来统计战舰的个数.(这个

LeetCode.1047-重复删除字符串中的所有相邻重复项

这是小川的第389次更新,第419篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第251题(顺位题号是1047).给定一个小写字母的字符串S,重复删除两个相邻且相等的字母. 我们在S上反复删除,直到我们再也无法删除. 在完成所有此类重复删除后返回最后一个字符串.保证答案是独一无二的. 例如: 输入:"abbaca" 输出:"ca" 说明:在"abbaca"中我们可以删除"bb",因为字母相邻且相等

[LeetCode] 349 Intersection of Two Arrays &amp; 350 Intersection of Two Arrays II

这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/ 350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ 题目&解法

LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,

LeetCode OJ - Sum Root to Leaf Numbers

这道题也很简单,只要把二叉树按照宽度优先的策略遍历一遍,就可以解决问题,采用递归方法越是简单. 下面是AC代码: 1 /** 2 * Sum Root to Leaf Numbers 3 * 采用递归的方法,宽度遍历 4 */ 5 int result=0; 6 public int sumNumbers(TreeNode root){ 7 8 bFSearch(root,0); 9 return result; 10 } 11 private void bFSearch(TreeNode ro

LeetCode OJ - Longest Consecutive Sequence

这道题中要求时间复杂度为O(n),首先我们可以知道的是,如果先对数组排序再计算其最长连续序列的时间复杂度是O(nlogn),所以不能用排序的方法.我一开始想是不是应该用动态规划来解,发现其并不符合动态规划的特征.最后采用类似于LRU_Cache中出现的数据结构(集快速查询和顺序遍历两大优点于一身)来解决问题.具体来说其数据结构是HashMap<Integer,LNode>,key是数组中的元素,所有连续的元素可以通过LNode的next指针相连起来. 总体思路是,顺序遍历输入的数组元素,对每个