leetcode 419

此题技巧题,可以通过试试几个简单的例子,能够发现结果。我们记录X出现的总次数,然后记录X四周出现的X的数目,可以发现结果就是count-repeat/2,附代码,(emmmmm果然python和C++,C#,java 这些语言没啥区别)

class Solution:
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        count = 0
        repeat = 0
        if len(board) == 0:
            return 0
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == "X":
                    count += 1
                    if i > 0:
                        if board[i-1][j] == "X":
                            repeat += 1
                    if j > 0:
                        if board[i][j-1] == "X":
                            repeat += 1
                    if i < len(board) - 1:
                        if board[i+1][j] == "X":
                            repeat += 1
                    if j < len(board[0]) - 1:
                        if board[i][j+1] == "X":
                            repeat += 1
        return int(count - repeat/2)

猜你喜欢

转载自blog.csdn.net/bengepai/article/details/82141875
今日推荐