腾讯2020 秋招笔试算法第二题

题目描述:
给你一个n*m的二维矩阵,每个格子有且仅有`.`和`x`两种状态。
`.`的格子没破损最多可以走2次,再走会掉下去;
`x`的格子已破损(我理解的是可以走1次,也有同学理解的是1次都不能走),再走会掉下去;
让你判断能不能从起点(start_x,start_y)走到(end_x,end_y),并且走到(end_x,end_y)刚好能掉下去。
if __name__ == "__main__":
    t = int(input())
    while t > 0:
        n, m = [int(x) for x in input().strip().split(' ')]
        net = []
        for i in range(n):
            tem = list(input())
            net.append(tem)
        x0, y0 = [int(x) for x in input().strip().split(' ')]
        x1, y1 = [int(x) for x in input().strip().split(' ')]
        x_tar, y_tar = x1-1, y1-1
        dx = [-1, 0, 1, 0]
        dy = [0, 1, 0, -1]
        stack = []
        stack.append((x0-1, y0-1))
        while stack != []:
            x, y = stack[-1]
            if x == x_tar and y == y_tar:
                if net[x][y] == 'X':
                    print('YES')
                else:
                    cnt = 0
                    if 0 <= x-1 < n and 0 <= y < m and net[x-1][y]=='.': cnt += 1
                    if 0 <= x < n and 0 <= y+1 < m and net[x][y+1]=='.': cnt += 1
                    if 0 <= x+1 < n and 0 <= y < m and net[x+1][y]=='.': cnt += 1
                    if 0 <= x < n and 0 <= y-1 < m and net[x][y-1]=='.': cnt += 1
                    if cnt < 2: print('NO')
                    else: print('YES')
                break
            flag = False
            for i in range(4):
                x_ = x + dx[i]
                y_ = y + dy[i]
                if 0 <= x_ < n and 0 <= y_ < m and net[x_][y_] == '.' and (x_, y_) not in stack:
                    stack.append((x_, y_))
                    flag = True
                    break
            if flag == False:
                stack.pop(-1)
                net[x][y] = 'X'

        if stack == []:
            print('NO')

        t -= 1

能够通过测试样例,不知道对不对 ,求指点
#腾讯##笔试题目##算法工程师#
全部评论
没有做,只是猜一下。如果x能走的话,那就无所谓能不能走到,一定能走到的
点赞 回复 分享
发布于 2019-08-19 19:13

相关推荐

12-11 14:24
门头沟学院 Java
牛客35720396...:不要用boss,全是骗
点赞 评论 收藏
分享
评论
点赞
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务