【leetcode】419. Battleships in a Board

It ’s hard to think

board = [['X', ' . ', ' . '],

                   [' . ', ' . ', 'X'],

                   [' . ', ' . ', 'X'],

                   [' . ', ' . ', ' X ', ]]

Record my struggles:

if not filter(lambda x:x<len(board[0]),[row.count('X') for row in board]):
            if board[0].count('X')>0:
                return 1
            else:
                return 0  #[['X']]
        #maxx = max(filter(lambda x:x<len(board[0]),[row.count('X') for row in board]))
        maxx = max(lambda x:x<len(board[0]),[row.count('X') for row in board])
        if maxx != len(board[0])
        maxx = max(maxx, max(filter(lambda x:x<len(board),[[row[col] for row in board].count('X') for col in range(len(board[0])) ])))
        if maxx==0:
            if board[0].count('X')>0:
                return 1
            else:
                return 0    #[['X','X','X']]

        return maxx 

Ah later, my thoughts were slightly more correct, but I only thought of how to judge the right and the bottom to summarize the boat, but did not think of excluding the left and the upper. .

Note that python does not have ||, and &, |, ^ respectively represent the bit operation of NAND, the logical operation is honest and, or, not

28.91%

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        cnt = 0
        for i in range(len(board)):
            for j in range(len(board[0])):
                #board[i][j] right:board[i][j+1] down:board[i+1][j]
                if board[i][j]=='X'and(i==0 or board[i-1][j]=='.')and(j==0 or board[i][j-1]=='.'):
                    cnt += 1
        return cnt

-----------------------------------------

Shock! The first time I encountered 100% 42ms

note1: Judging (greater than or less than) is more efficient than (not equal to or equal to)

note2: zip () returns a list of tuples

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        return sum(zip(r,['.']+r,p or'.'*len(r)).count(tuple('X..'))for r,p in zip(board,[0]+board))

Suspected derivation process? . .

def countBattleships(self, b):
   #return sum(all([b[y][x]=='X',x<1 or b[y][x-1]!='X',y<1 or b[y-1][x]!='X']) for y in range(len(b)) for x in range(len(b[0])))
   #return sum(all([b[y][x]>'.', x<1 or b[y][x-1] <'X',y<1 or b[y-1][x]< 'X']) for y in range(len(b)) for x in range(len(b[0])))
   #return sum(all([b[y][x]>'.', x<1 or 'X'>b[y][x-1], y<1 or 'X'>b[y-1][x]]) for y in range(len(b))for x in range(len(b[0])))
   #return sum(all([c>'.',x<1or'X'>r[x-1],y<1or'X'>b[y-1][x]])for y,r in enumerate(b) for x,c in enumerate(r))
    return sum(zip(r,['.']+r,p or'.'*len(r)).count(tuple('X..'))for r,p in zip(b,[0]+b))

------------------------------------

Tian Lalu is another 100%. In fact, all are variants of the first idea. The advantage of this one is that the judgment conditions are optimized when traversing each point. Excluded faster is equivalent to faster counting.

As well as being deceived, other variable spaces are used here. Strictly speaking, the memory that does not meet the requirements of the title is O (1)

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        cols = len(board)
        rows = len(board[0])
        ct = 0
        for c in xrange(cols):
            for r in xrange(rows):
                # We count a battleship only first time we see it. If a battleship piece 'X'
                # is encountered, it is only new if neither the upper or left components are not also
                # pieces of the same battleship. These prior indices are guarenteed to already be explored by 
                # the time we get to the current board index.
                if board[c][r] != 'X':
                    continue
                if r > 0 and board[c][r - 1] == 'X':
                    continue
                if c > 0 and board[c - 1][r] == 'X':
                    continue
                ct += 1
        return ct


Intelligent Recommendation

Leetcode 419. Battleships in a board (algorithm)

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 v...

419. Battleships in a Board

https://leetcode.com/problems/battleships-in-a-board/ 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....

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 v...

[LC] 419. Battleships in a Board

Normally, this kind of dfs is used to find how many islands are in a picture. That is, dfs travels to an island or battleship and then mark visited. This question is also possible. Of course, follow u...

Leetcode study notes: #419. Battleships in a Board

Leetcode study notes: #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 ...

More Recommendation

【leetcode】419. Battleships in a Board(C++ &amp; Python)

419. Battleships in a Board Topic link 419.1 Subject description: Given an 2D board, count how many battleships are in it. The battleships are represented with ‘X’s, empty slots are repres...

[Leetcode] 419. Battleships in a Board Problem Solving Report

topic: 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 rece...

leetcode 419. Battleships in a Board number of battleships + a novel loop traversal

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: Y...

419 Battleships in the deck of the ship on a Board

Given a two-dimensional deck, calculate how many warships. Ships with 'X', said gap by '' represents. You need to observe the following rules: To give you an effective deck, composed only by warships ...

Use useEffect method to achieve useState callback effect

When using hook's useState, we need to execute a callback method after updating the data, but useState does not have a callback, what should we do? Use useEffect to achieve the same effect Problem env...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top