2019年8月18日

騰訊筆試的第二題

三種方法:遞歸,基於棧的DFS和基於隊列的BFS,其中棧容易溢出,BFS記錄不了最後的路徑。python

import sys

if __name__ == "__main__":
    t = int(sys.stdin.readline().strip())

    for ti in range(t):

        n, m = list(map(int, sys.stdin.readline().strip().split()))
        maze = []
        for x in range(n):
            s = sys.stdin.readline().strip().replace('X', "1").replace(".", "0")
            maze.append(list(map(int, list(s))))

        start = list(map(int, sys.stdin.readline().strip().split()))
        end = list(map(int, sys.stdin.readline().strip().split()))
        start = tuple([j - 1 for j in start])
        end = tuple([j - 1 for j in end])


        def mark(maze, pos):
            maze[pos[0]][pos[1]] = 2

        path = []
        dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]

        #遞歸
        def find_path_re(maze, pos, end):
            mark(maze, pos)

            if pos == end:
                print(pos, end=" ")
                path.append(pos)
                for i in range(4):
                    # check
                    nextp = pos[0] + dirs[i][0], pos[1] + dirs[i][1]
                    if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or \
                            maze[nextp[0]][nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                        continue
                    else:
                        return True, path
                return False, path

            for i in range(4):
                # check
                nextp = pos[0] + dirs[i][0], pos[1] + dirs[i][1]
                if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or maze[nextp[0]][
                    nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                    continue
                else:
                    if find_path_re(maze, nextp, end)[1]:
                        print(pos, end=" ")
                        path.append(pos)
                        return True, path

            return False, path
        # DFS
        def find_path_dfs(maze, start ,end):
            st = []
            st.append(start)
            mark(maze, start)

            if start == end:
                for i in range(4):
                    # check
                    nextp = end[0] + dirs[i][0], end[1] + dirs[i][1]
                    if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or \
                            maze[nextp[0]][nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                        continue
                    else:
                        print(st)
                        return True
                return False

            while st!=[]:

                pos = st.pop()
                mark(maze, pos)

                for i in range(4):
                    # check
                    nextp = pos[0] + dirs[i][0], pos[1] + dirs[i][1]
                    if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or maze[nextp[0]][
                        nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                        continue
                    else:
                        if nextp == end:
                            for i in range(4):
                                # check
                                nextp = end[0] + dirs[i][0], end[1] + dirs[i][1]
                                if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or \
                                        maze[nextp[0]][nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                                    continue
                                else:
                                    st.append(pos)
                                    print(st)
                                    return True, st
                            return False
                        st.append(pos)
                        st.append(nextp)
                        break
            return False, st
        
        #BFS
        def find_path_bfs(maze, start ,end):

            qu = []
            qu.append(start)
            mark(maze, start)

            if start == end:
                for i in range(4):
                    # check
                    nextp = end[0] + dirs[i][0], end[1] + dirs[i][1]
                    if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or \
                            maze[nextp[0]][nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                        continue
                    else:
                        print(qu)
                        return True
                return False

            while qu!=[]:

                pos = qu.pop(0)
                path.append(pos)
                mark(maze, pos)

                for i in range(4):
                    # check
                    nextp = pos[0] + dirs[i][0], pos[1] + dirs[i][1]
                    if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or maze[nextp[0]][
                        nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                        continue
                    else:
                        if nextp == end:
                            path.append(pos)
                            path.append(end)
                            for i in range(4):
                                # check
                                nextp = end[0] + dirs[i][0], end[1] + dirs[i][1]
                                if nextp[0] < 0 or nextp[1] < 0 or nextp[0] >= len(maze) or nextp[1] >= len(maze[1]) or \
                                        maze[nextp[0]][nextp[1]] == 1 or maze[nextp[0]][nextp[1]] == 2:
                                    continue
                                else:
                                    print(path)
                                    return True
                            return False
                        qu.append(nextp)
            return False
        #可視化路徑
        def see_path(maze, path, start, end):  # 使尋找到的路徑可視化
            for i, p in enumerate(path):
                maze[p[0]][p[1]] = 3
            maze[start[0]][start[1]] = "S"
            maze[end[0]][end[1]] = "E"
            print("\n")
            for r in maze:
                for c in r:
                    if c == 3:
                        print('\033[0;31m' + "*" + " " + '\033[0m', end="")
                    elif c == "S" or c == "E":
                        print('\033[0;34m' + c + " " + '\033[0m', end="")
                    elif c == 2:
                        print('\033[0;32m' + "#" + " " + '\033[0m', end="")
                    elif c == 1:
                        print('\033[0;;40m' + " " * 2 + '\033[0m', end="")
                    else:
                        print(" " * 2, end="")
                print()


        result, path = find_path_re(maze, start, end)
        print(result)
        see_path(maze, path, start, end)

""" 2 4 6 X...XX ...XX. .X..X. ...... 1 6 2 2 9 47 ....X.X.X.X...X..X.....X..X..X..X....X.X...X..X XX..X...X.........X...X...X..X.XX......X...X... ..XX...X.......X.....X.....X.XX..X.....X..XX... .X...XX....X...X.......X.X...X......X.X.X...... X......X..X.XXX....X...X.X.XX..X.......X....X.X ....XX.X...X.XXX.X..XX.XXX...XXX..XX.X.X.XX..XX .........X...X.XXXX...XX.XX....XX..X...X....X.. .............X....XXXX....X.X...XX.XX.X.X..X... .X......X.....X......X......X.X.X..X.......XXX. 2 34 7 30 """

複製代碼

頭條面試題:計算字符串表達式

LeetCode題目面試

解釋數組

本身寫的代碼,沒有考慮小數,負數和大整數,後續完善一下app

#計算單獨的表達式
def eval(S):
    opt_set1 = ("*", "/")
    opt_set2 = ("+", "-")

    st = [S[0]]

    for i in range(1, len(S)):
        if S[i - 1] not in opt_set1:
            st.append(S[i])
        else:
            st.pop()
            if S[i - 1] == "*":
                d = int(st.pop()) * int(S[i])
            else:
                d = int(st.pop()) / int(S[i])
            st.append(str(int(d)))

    if len(st) == 1:
        return int(st[0])

    res = 0
    for i in range(1, len(st)):
        if st[i - 1] not in opt_set2:
            continue
        if st[i - 1] == "+":
            res += int(st[i - 2]) + int(st[i])
        else:
            res += int(st[i - 2]) - int(st[i])

    return res

## 先去括號
def calc(S):
    st = []
    for s in S:
        if s != ')':
            st.append(s)
        else:
            temp = ""
            temp1 = st.pop()
            while temp1 != '(':
                temp += temp1
                temp1 = st.pop()
            st.append(str(eval(temp)))

    return eval("".join(st))


print(calc("(4+2)/2+(3*3)"))

複製代碼

頭條面試代碼題:跳躍遊戲

頭條面試代碼題

一個數組a[0...n-1],求a[j]-a[i]的最大值+求a[i]-a[j]的最大值,其中i>j -博客spa

頭條面試代碼題

862. 和至少爲 K 的最短子數組.net

相關文章
相關標籤/搜索