Coding Test/programmers

[Python] 파이썬 프로그래머스 거리두기 확인하기

파송송 2022. 8. 23. 22:27
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/81302

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


아래의 코드를 사용하여 P의 위치를 다 구해서 2개씩 짝지어지는 경우의 수를 구함

list(combinations(P_pla,2))

파란색 원이 그려진 P를 기준으로 4개의 경우의 수를 if문으로 만들고 사이에 O가 들어가면 0을 return 해주는 함수를 만듦

from itertools import combinations

def check(places, com_pla):
    for i in com_pla:
        try:
            if (abs(i[0][0] - i[1][0]) + abs(i[0][1] - i[1][1])) == 1:
                return 0
            if (abs(i[0][0] - i[1][0]) + abs(i[0][1] - i[1][1])) == 2:
                if i[0][0] == i[1][0]:
                    if places[i[0][0]][i[0][1] + 1] == 'O':
                        return 0

                if i[0][1] == i[1][1]:
                    if places[i[0][0] + 1][i[0][1]] == 'O':
                        return 0
                if i[0][0] + 1 == i[1][0] and i[0][1] -1 == i[1][1]:
                    if places[i[0][0]][i[0][1] - 1] == 'O' or places[i[0][0] + 1][i[0][1]] == 'O':
                        return 0
                elif i[0][0] + 1 == i[1][0] and i[0][1] + 1 == i[1][1]:
                    if places[i[0][0]][i[0][1] + 1] == 'O' or places[i[0][0] + 1][i[0][1]] == 'O':
                        return 0
        except:
            pass
    return 1

def solution(places):
    answer = list()
    for places in places:
        P_pla = list()
        place = [j for j in places]

        for i in range(5):
            for j in range(5):
                if place[i][j] == 'P':
                    P_pla.append([i,j])


        com_pla = list(combinations(P_pla,2))
        answer.append(check(places, com_pla))

    return answer


다른 사람의 코드

def solution(places):
    result = []
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]

    def f(i, j, cnt):
        nonlocal good
        if cnt >2 : return
        if -1<i<5 and -1<j<5:
            if graph[i][j] == 'X':
                return

            if cnt != 0 and graph[i][j] == 'P':
                good = 0
                return

            graph[i][j] = 'X'

            for w in range(4):
                ni = i+dx[w]
                nj = j+dy[w]
                f(ni, nj, cnt+1)

    for case in places:
        graph = [list(r) for r in case]
        good = 1
        for i in range(5):
            for j in range(5):
                if graph[i][j]=='P':
                    f(i,j,0)

        result.append(good)
    return result

728x90