CareerCup maximum sum in n*n num array

大憨熊 提交于 2020-01-13 01:08:59

Given a n*n array like the following example. A man could only move up down left and right without oblique movement. BTW, the man could only arrive when num[i][j] is a number instead of '*'. At the same time, no num circle could be generated in n*n array. How could we get the maximum num sum?

nums = [['*','*','4','*','*','1','*'],
['*','1','2','3','*','*','*'],
['*','1','*','3','*','*','*'],
['*','*','*','*','1','*','*'],
['*','*','1','1','3','1','*'],
['*','*','3','*','88','*','*'],
['*','*','1','1','*','*','1233']];

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

Solution:

The condition "no num circle could be generated in n*n array" is significant. The num area could be a tree!!! The problem could be transformed into the maximum path between two tree node. If writting recursive codes, two return values are required; else a accumulated dict is required. 

def is_valid(nums, vis, x, y, n):
    return x >= 0 and x < n and y >= 0 and y < n and nums[x][y] != '*' and vis[x][y] == 0

def dfs(nums, vis, x, y, n):
    valid = is_valid(nums, vis, x, y, n)
    if (valid == False):
        return 0,0
    vis[x][y] = 1
    max_depth, max_gold = int(nums[x][y]), int(nums[x][y])
    depths = []
    for dx,dy in [(1,-1),(-1,-1),(1,1),(-1,1)]:
        nx,ny = x+dx,y+dy
        if (is_valid(nums, vis, nx, ny, n) == True):
            c_depth, c_gold = dfs(nums, vis, nx, ny, n)
            depths.append(c_depth)
    sorted_depth = sorted(depths, reverse=True)
    if len(sorted_depth) == 1:
        max_depth, max_gold = int(nums[x][y])+depths[0], int(nums[x][y])+depths[0]
    elif (len(sorted_depth) > 1):
        max_depth, max_gold = int(nums[x][y])+depths[0], int(nums[x][y])+depths[0]+depths[1]
    return max_depth, max_gold

def cal_max_gold(nums):
    res = 0
    n = len(nums)
    vis = [[0 for j in range(n)] for i in range(n)]
    for i in range(n):
        for j in range(n):
            max_depth, max_gold = dfs(nums, vis, i, j, n)
            if (max_gold > res):
                res = max_gold
    return res

nums = [['*','*','4','*','*','1','*'],
['*','1','2','3','*','*','*'],
['*','1','*','3','*','*','*'],
['*','*','*','*','1','*','*'],
['*','*','1','1','3','1','*'],
['*','*','3','*','88','*','*'],
['*','*','1','1','*','*','1233']];
res = cal_max_gold(nums)
print(res)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!