Skip to content

Commit

Permalink
solve(programmers): LV3_길 찾기 게임_py
Browse files Browse the repository at this point in the history
# id: 문제 id를 숫자로 작성
# categories : 해당 문제의 유형을 ,로 구분하여 작성
# tags : 해당 문제의 태그를 ,로 구분하여 작성
# time : 해당 문제 풀이에 걸린 시간을 분단위 숫자로 작성
# try : 해당 문제에 몇번의 시도를 했는지 숫자로 작성
# help: 해당 문제에 외부의 도움을 받았는지 true/false로 작성
# url : 해당 문제의 url을 작성
id: 42892
categories: [Tree,DFS]
tags: []
time: 80
try: 2
help: false
url: https://school.programmers.co.kr/learn/courses/30/lessons/42892
  • Loading branch information
gogumaC committed Aug 7, 2024
1 parent 0da7cdf commit 5d40086
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions src/programmers/level_1/Tree/LV3_길찾기게임.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from collections import deque
import sys

sys.setrecursionlimit(1000000)

class Node:
def __init__(self,value,x,y,left=None,right=None,parent=None):
self.parent=parent
self.left=left
self.right=right
self.value=value
self.x=x
self.y=y

def create_graph(root,node_info,new_nodes):

nodes=[Node(i,v[0],v[1]) for i,v in enumerate(node_info)]

for new_node in new_nodes:
s=deque()
s.append(nodes[root])

ni=new_node[2]
new=nodes[ni]

while s:
current=s.pop()

if current.y>new.y: #밑으로 내려감
if current.x>new.x: #왼쪽의 경우
if current.left==None:
current.left=new
new.parent=current
break
else:
s.append(current.left)
else:
if current.right==None:
current.right=new
new.parent=current
break
else:
s.append(current.right)

return nodes


def pre_order(graph,current,path=[]):

path.append(current.value+1)

if current.left!=None:
pre_order(graph,current.left,path)
if current.right!=None:
pre_order(graph,current.right,path)
return path

def post_order(graph,current,path=[]):

if current.left!=None:
post_order(graph,current.left,path)
if current.right!=None:
post_order(graph,current.right,path)
path.append(current.value+1)
return path


def solution(nodeinfo):
nodes=[]
for i,(x,y) in enumerate(nodeinfo):
nodes.append((-y,x,i,x,y))
nodes.sort()
root=nodes[0][2]

graph=create_graph(root,nodeinfo,nodes)

pre=pre_order(graph,graph[root])
post=post_order(graph,graph[root])

answer = [pre,post]
return answer

0 comments on commit 5d40086

Please sign in to comment.