본문 바로가기
코딩테스트

게임 맵 최단거리

by 느림보어른 2021. 6. 1.

문제풀이

효율성 실패

import copy
def remove_values_from_list(the_list, val):
    return [value for value in the_list if value != val]

def move(my_point, maps, y_len, x_len, count):
    count += 1
    time = 0
    
    counts= []
    
    maps[my_point[0]][my_point[1]] = 0
    new_maps = copy.deepcopy(maps)
    
    if my_point[0] == y_len-1 and my_point[1] == x_len-1:
        return count
    
    if(my_point[0] != 0 and maps[my_point[0]-1][my_point[1]] != 0):
        time += 1
        new_point = my_point[:]
        new_maps = copy.deepcopy(maps)
        new_point[0] -= 1
        counts.append(move(new_point, new_maps, y_len, x_len, count))
    if(my_point[0] != y_len-1 and maps[my_point[0]+1][my_point[1]] != 0):
        time += 1
        new_point = my_point[:]
        new_maps = copy.deepcopy(maps)
        new_point[0] += 1
        counts.append(move(new_point, new_maps, y_len, x_len, count))
    if(my_point[1] != 0 and maps[my_point[0]][my_point[1]-1] != 0):
        time += 1
        new_point = my_point[:]
        new_maps = copy.deepcopy(maps)
        new_point[1] -= 1
        counts.append(move(new_point, new_maps, y_len, x_len, count))
    if(my_point[1] != x_len-1 and maps[my_point[0]][my_point[1]+1] != 0):
        time += 1
        new_point = my_point[:]
        new_maps = copy.deepcopy(maps)
        new_point[1] += 1
        counts.append(move(new_point, new_maps, y_len, x_len, count))
        
    counts = remove_values_from_list(counts, -1)
        
    if time == 0 or len(counts) == 0:
        return -1
    else:
        min_count = min(counts)
        return min_count

def solution(maps):
    my_point = [0, 0]
    count = 0
    
    y_len = len(maps)
    x_len = len(maps[0])
    
    answer = move(my_point, maps, y_len, x_len, count)
    
    return answer

알고리즘

현재 효율성 실패로 아직 해결하지 못한 문제이다.

얕은 복사, 깊은 복사

출처

문제: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

 

코딩테스트 연습

기초부터 차근차근, 직접 코드를 작성해 보세요.

programmers.co.kr

'코딩테스트' 카테고리의 다른 글

실패율  (0) 2021.06.03
오픈채팅방  (0) 2021.06.01
3진법 뒤집기  (0) 2021.06.01
키패드 누르기  (0) 2021.05.30
튜플  (0) 2021.05.29