본문 바로가기

코딩 테스트/DFS, BFS12

블록 이동하기 p. 355 BFS from collections import deque def get_next_pos(pos, board): next_pos = [] # 반환 결과 (이동 가능한 위치들) pos = list(pos) # 현재 위치 정보를 리스트로 변환(집합->리스트) pos1_x, pos1_y, pos2_x, pos2_y = pos[0][0], pos[0][1], pos[1][0], pos[1][1] # (상, 하, 좌, 우)로 이동하는 경우에 대해서 처리 dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] for i in range(4): pos1_next_x, pos1_next_y, pos2_next_x, pos2_next_y = pos1_x + dx[ i], pos1_y + dy[.. 2021. 2. 5.
인구 이동 p.353 python3로 하니까 시간초과 pypy3로 함 import sys from collections import deque input=sys.stdin.readline n,l,r=map(int, input().split()) A=[] for i in range(n): A.append(list(map(int, input().split()))) dx=[-1,1,0,0] dy=[0,0,-1,1] day_cnt=0 # day count while True: # 더이상 연합이 만들어지지 않을 때까지 uni_flag=0 # 연합이 만들어졌는지 체크 day_visit=[[0]*n for _ in range(n)] # 방문한 나라 체크 (하루마다 초기화) for i in range(n): for j in ra.. 2021. 2. 3.
감시 피하기 p.351 방법 1 import sys from itertools import combinations input=sys.stdin.readline n=int(input()) map=[] temp_map=[[0]*n for _ in range(n)] o=[] # 장애물을 놓을 수 있는 곳의 위치 t=[] # 선생님의 위치 for i in range(n): temp_o=list(input().split()) map.append(temp_o) for j in range(n): if temp_o[j] == 'X': o.append((i,j)) elif temp_o[j]=='T': t.append((i,j)) oc=list(combinations(o,3)) dx=[-1,1,0,0] dy=[0,0,-1,1] fou.. 2021. 1. 31.
연산자 끼워넣기 p.349 permutations로 풀려다가 시간 초과가 나서 dfs로 변경 ㅠㅠㅠ import sys input=sys.stdin.readline n=int(input()) num=list(map(int, input().split())) add,sub,mul,div=map(int, input().split()) # 연산자 받기 max_result=-1e9 min_result=1e9 def dfs(i, temp, add, sub, mul, div): global max_result, min_result if i==n: max_result=max(temp, max_result) min_result=min(temp, min_result) else: if add: dfs(i+1, temp+num[i], add.. 2021. 1. 31.
괄호 변환 p.346 DFS/BFS 문제라기 보단 구현 문제에 가까움 def divide(p): count=0 for i in range(len(p)): if p[i]=='(': count+=1 else: count-=1 if count == 0: return i def iscorrect(u): count = 0 for i in range(len(u)): if u[i]==')': if count == 0: return False count -= 1 else: count +=1 return True def solution(p): answer = '' if p==answer: return answer index=divide(p) u,v=p[:index+1],p[index+1:] if iscorrect(u) == Tru.. 2021. 1. 29.
경쟁적 전염 p.345 import sys from collections import deque input=sys.stdin.readline n,k=map(int, input().split()) test=[] data=[] for i in range(n): test.append(list(map(int, input().split()))) for j in range(n): if test[i][j] != 0: # 바이러스 종류, 시간, 좌표x, 좌표y data.append((test[i][j],0,i,j)) s,x,y=map(int, input().split()) data.sort() q=deque(data) dx=[-1,1,0,0] dy=[0,0,-1,1] while q: virus, _s, _x, _y=q.poplef.. 2021. 1. 27.