[프로그래머스] Python 공원 산책 Level1 - 연습문제

swb·2024년 1월 19일

프로그래머스

목록 보기
8/23

문제 바로가기

접근 방법

  • 크게 어려운 문제는 아닌 것 같다.
  1. 동서남북 지시대로 움직인다.
  2. 격자를 벗어나는 경우와 X인 경우를 고려한다.
  • 까다로운 점은 명령이 2인데 1만큼 떨어진 곳에 X거나 벗어나는 것을 생각해야 한다.
    -> 위치 최신화를 통해 해결

코드

def solution(park, routes):
	# 2차원 배열로 만들기
    graph = [list(row) for row in park]

	# 시작 y, x 좌표 찾기
    for i, start in enumerate(graph):
        if 'S' in start:
            y = i
            x = start.index('S')

	# 명령 수 만큼 반복
    for i in range(len(routes)):
    	# 방향, 거리
        d, step = routes[i].split()
        # 움직이는 좌표
        ny = y
        nx = x

        for j in range(int(step)):

            if d == 'E' and nx != len(graph[0]) - 1 and graph[ny][nx + 1] != 'X':
                nx += 1
                if j == int(step) - 1: # 거리만큼 움직였다면 OK라는 뜻
                    x = nx

            elif d == 'W' and nx != 0 and graph[ny][nx - 1] != 'X':
                nx -= 1
                if j == int(step) - 1:
                    x = nx

            elif d == 'N' and ny != 0 and graph[ny - 1][nx] != 'X':
                ny -= 1
                if j == int(step) - 1:
                    y = ny

            elif d == 'S' and ny != len(graph) - 1 and graph[ny + 1][nx] != 'X':
                ny += 1
                if j == int(step) - 1:
                    y = ny


    
    return [y, x]
profile
개발 시작

0개의 댓글