Airbnb 面试题: 多米诺骨牌王国游戏

题目摘自

在Kingdomino的游戏中,玩家用多米诺骨牌制作王国,在游戏结束时你可能会到达一个看起来像上面的王国。相同类型的tile的每个连续块都是属性,每个属性的值是它的大小乘以其中的冠数。整个王国的得分是其中每个财产的得分总和。城堡不值得分。一个王国永远不会超过5x5,它可能会有洞
在上图所示的王国中,玩家将得到41分,由…组成。* 7个水平瓷砖,3个冠,21点* 1个普通瓷砖,2个冠,2个点* 2个沼泽瓷砖6个点,3个冠* 4格4瓦,2冠* 2个地砖2个冠4点
*不同尺寸的各种属性值0分,因为它们有0个
要求给你一个上面的board, 算出点数。

这游戏要是玩过会有不少优势 :joy:

先确定卡牌的种类,也就是要求不同种类的岛屿面积,同时记下:crown:的数量?

目测可行(●°u°●)​ 」

感觉最重要的是这个算分规则,没理解错应该就是面积*皇冠数吧,啥叫可能有洞,就是没皇冠吧。城堡:european_castle:刨出去,目测写的时候要心细点。

嗯,对的

今天得空写了一下这道题,每个卡牌直接用class了,棋盘hard code写好的。欢迎指正~

class patch:
    def __init__(self,name,n):
        self.name = name
        self.crown = n
        self.visited = False

class Solution:
   
    def count_point(self,board):
        total_points = 0
        for r in range(len(board)):
            for c in range(len(board[0])):
                if board[r][c].crown > 0 and not board[r][c].visited:
                    self.tmp_num_crowns = 0
                    patch_area = self.area(r,c,board,board[r][c].name)
                    total_points += self.tmp_num_crowns * patch_area
        return total_points

    def area(self,x,y,board,pattern):
        """
        
        :param board: 
        :return: how many patches with same type connected 
        """
        if x < 0 or y < 0 or x >len(board)-1 or y > len(board[0])-1 or board[x][y].name != pattern or board[x][y].visited or board[x][y].name == "castle":
            return 0

        board[x][y].visited = True
        self.tmp_num_crowns += board[x][y].crown
        return 1+self.area(x-1,y,board,pattern) + self.area(x+1,y,board,pattern) + self.area(x,y-1,board,pattern) + self.area(x,y+1,board,pattern)

board = [
    [patch("sand",0),patch("water",1),patch("water",1),patch("water",0),patch("grass",2)],
    [patch("water",0),patch("water",0),patch("forest",0),patch("forest",0),patch("forest",0)],
    [patch("water",0),patch("water",1),patch("forest",0),patch("swamp",2),patch("swamp",1)],
    [patch("sand",0),patch("castle",0),patch("sand",1),patch("sand",0),patch("sand",0)],
    [patch("swamp",0),patch("cave",2),patch("cave",0),patch("sand",1),patch("forest",0)]
]

s = Solution()
print(s.count_point(board))
1 Like

谢谢帮忙调整了下格式:rofl:

这种代码就不要出现了,改成 !board[r][c].visited

好的,更正了一下。

弱弱的问一句楼主,倒水题是啥题呢?

参考看