京东秋招笔试--消消乐

消消乐,>= 3个可消除掉,重力掉落,问最后最少剩几个

样例:(输入必须5 * 5, 只有1,2,3三种类型)
3 1 2 1 1
1 1 1 1 2
1 1 1 1 1
1 1 1 1 1
3 1 2 2 2
输出:4
因为,消除最后结果为:
3 0 2 0 0
0 0 0 0 2
3 0 0 0 0

import sys
from collections import defaultdict
direction = [[1,0],[0,1],[-1,0],[0,-1]]
grid = []
for i in range(5):
    line = sys.stdin.readline().strip()
    nums = list(map(int, line.split()))
    grid.append(nums)

def del_grid():
    global grid
    s = []
    for i in range(len(grid)):
        if(grid[i].count(0) != 5):
            s.append(grid[i])        
    return s

def judge(r, c):
    global grid     
    if(r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0])):
        return False
    return True

def maxAreaOfIsland(): 
    global grid        
    Area = 0
    i, j = 0, 0    
    while(i < len(grid) and j < len(grid[0])):
        vis = [[0 for k in range(len(grid[0]))] for w in range(len(grid))]
        if(grid[i][j] != 0):
            tar = grid[i][j]            
            Area = dfs(i, j, tar, vis)            
            if(Area >= 3):
                a = dfs_(i, j, tar)
                grid = del_grid()
                maxAreaOfIsland()
        j = j + 1
        if(j == len(grid[0])):
            i += 1
            j = 0
    return

def dfs_(r, c, tar) :
    global grid
    if (judge(r,c) == False or grid[r][c] != tar):
        return 0
    grid[r][c] = 0
    area = 1
    for d in direction:
        area += dfs_(r + d[0], c + d[1], tar)
    return area

def dfs(r, c, tar, vis):
    global grid        
    if (judge(r,c) == False or grid[r][c] != tar or vis[r][c] == 1):
        return 0    
    vis[r][c] = 1
    area = 1
    for d in direction:
        area += dfs(r + d[0], c + d[1], tar, vis)
    return area

t = 0
maxAreaOfIsland()
for i in range(len(grid)):
    t += (grid[i].count(1) + grid[i].count(2)+ grid[i].count(3))
print(t)

你可能感兴趣的:(春秋招笔试)