GithubHelp home page GithubHelp logo

backjun_algorithm's People

Watchers

 avatar  avatar

backjun_algorithm's Issues

11724 백준

-- coding: utf-8 --

"""
Created on Sun Jan 5 16:08:23 2020

@author: YSW
"""
import sys

global graph
global visit

def dfs(start):

visit[start]=True

for node in graph[start]:
    if visit[node]==False:
        visit[node]=True
        dfs(node)

n,v=map(int,sys.stdin.readline().split())
graph=[[]for _ in range(n+1)]
visit=[False] * (n+1)
count=0

for _ in range(v):
col,row=map(int,sys.stdin.readline().split())
graph[col].append(row)
graph[row].append(col)

for i in range(1,n+1):
if visit[i]==False:
dfs(i)
count = count + 1
print(count)

dfs 문제 푸는 순서

13023-1260-11724-1707- 2667-4963-나이트,비숍문제-2178-7576-1697-14226-2206-3055

덱을 사용 13549 - 1261

14226

-- coding: utf-8 --

"""
Created on Sun Jan 12 14:25:53 2020
@author: YSW
"""

S=int(input())
S_MAX=1001
visit=[[-1]*S_MAX for _ in range(S_MAX)]
visit[1][0]=0
q=[]
q.append([1,0]) #s,c 1,0은 초기 입력값

while q:

node_s,node_c=q.pop(0)

if node_s==S:
    print(visit[node_s][node_c])
    break

if visit[node_s][node_s]==-1:
    visit[node_s][node_s]=visit[node_s][node_c] + 1
    q.append([node_s,node_s])

if 0<=node_s+node_c<=S_MAX and visit[node_s+node_c][node_c]==-1:
    visit[node_s+node_c][node_c]=visit[node_s][node_c] + 1
    q.append([node_s+node_c,node_c])
    
if 0<=node_s-1<=S_MAX and visit[node_s-1][node_c]==-1:
    visit[node_s-1][node_c]=visit[node_s][node_c] + 1
    q.append([node_s-1,node_c])

백줌 섬문제

https://www.acmicpc.net/submit/4963/16874314

def bfs(v):
q = []
q.append(v)

while q:
    v = q.pop(0)
    for a in range(8):
        i = v[0] + di[a]
        j = v[1] + dj[a]
        if 0 <= i <= h-1 and 0 <= j <= w-1 and ocean[i][j]:
            ocean[i][j] = 0
            q.append([i, j])

di = [-1, -1, -1, 0, 0, 1, 1, 1]
dj = [-1, 0, 1, -1, 1, -1, 0, 1]

while True:

w, h = map(int, input().split())
if w == 0 and h == 0:
    break
ocean = [list(map(int, input().split())) for _ in range(h)]
cnt = 0

for i in range(h):
    for j in range(w):
        if ocean[i][j]:
            cnt += 1
            bfs([i, j])

print(cnt)

https://www.acmicpc.net/problem/10828

import sys

class stack:

def __init__(self):
    self.buf=[]
    
def push(self, num):
    self.buf.append(num)    
    
def pop(self):
    if self.buf:
       print(self.buf.pop())
    else:
       print(-1)
     
def size(self):
       print(len(self.buf))    

def empty(self):       
    if self.buf:
        print(0)
    else:
        print(1)
    
def top(self):
    if self.buf:
        print(self.buf[-1])
    else:
        print(-1)

cnt=int(input())
buf_type=stack()

for i in range(cnt):

op=sys.stdin.readline().rstrip()
 
if op[:4]=='push':
    buf_type.push(int(op[4:]))        
if op[:3]=='top':
    buf_type.top()     
if op[:3]=='pop':
     buf_type.pop()   
if op[:4]=='size':
    buf_type.size()   
if op[:5]=='empty':
    buf_type.empty()     

프로그래머스,완전검색 수포자

def solution(answers):
p = [[1, 2, 3, 4, 5],
[2, 1, 2, 3, 2, 4, 2, 5],
[3, 3, 1, 1, 2, 2, 4, 4, 5, 5]]
s = [0] * len(p)

for q, a in enumerate(answers):
    for i, v in enumerate(p):
        if a == v[q % len(v)]:
            s[i] += 1
return [i + 1 for i, v in enumerate(s) if v == max(s)]

백준,난쟁이문제

-- coding: utf-8 --

import itertools

#a=[20,7,23,19,10,15,25,8,13]
a=[]
for _ in range(9):
a.append(int(input()))

c_total=[]
c_sub_recov=[]
c_sub_recov_sum=[]
for i in range(0,len(a)+1):
c_total.append(list(itertools.combinations(a,i)))

for c_sub_total in c_total:
for c_sub in c_sub_total:
if len(c_sub) == 7:
c_sub_recov_sum.append(sum(list(c_sub)))
c_sub_recov.append(list(c_sub))

print(*sorted(c_sub_recov[c_sub_recov_sum.index(100)]),sep="\n")
#print('\n'.join(map(str, sorted(c_sub_recov[c_sub_recov_sum.index(100)]))))

백준 섬문제 re

def bfs(start_h,start_w):
queue=[]
queue.append([start_h,start_w])
earth[start_h][start_w]=0
while queue:
start_h,start_w = queue.pop(0)
for id in range(8):
sub_h = start_h + dh[id]
sub_w = start_w + dw[id]

        if 0<=sub_h<=h-1 and 0<=sub_w<=w-1 and earth[sub_h][sub_w]:
            earth[sub_h][sub_w]=0
            queue.append([sub_h,sub_w])

dh=[-1,-1,-1,0,1,1,1,0]
dw=[-1,0,1,1,1,0,-1,-1]

while True:
w,h=map(int,input().split())

if w==0 and h==0:
    break

earth=[]
for _ in range(h):
    earth.append(list(map(int, input().split())))

cnt = 0

for h_idx in range(h):
    for w_idx in range(w):
        if earth[h_idx][w_idx]:
            cnt +=1
            bfs(h_idx,w_idx)

print(cnt)

백준 알고리즘 재귀함수 정리

def solve(index, cnt, sum, {필요 입력값들 < 문자, 숫자, 연산자 >}, goal)

  • 1,2,3 더하기
    go(cnt, sum, goal)
    숫자 count해서 합 sum만드는 수

불가능한 경우) sum > goal
정답을 찾은 경우) sum==goal
다음 경우)

  • 1을 사용하는 경우, solve(index, cnt+1, sum+1, {필요 입력값들 < 문자, 숫자, 연산자 >}, goal)
  • 2을 사용하는 경우, solve(index, cnt+1, sum+2, {필요 입력값들 < 문자, 숫자, 연산자 >}, goal)
  • 3을 사용하는 경우, solve(index, cnt+1, sum+3, {필요 입력값들 < 문자, 숫자, 연산자 >}, goal)
  • 암호 만들기
    go(n, alpha, password, i)
    n: 만들어야 하는 암호 길이
    alpha: 사용할 수 있는 알파벳
    passwrod: 현재까지 만든 암호
    i:사용할지 말지 결정해야 하는 알파벳의 인덱스

불가능한 경우) i>=len(alpha)
정답을 찾은 경우) n==len(password)
다음 경우)

  • i번째 알파벳을 사용하는 경우 solve(i+1, cnt+1, password+1, {필요 입력값들 < alpha - 1, 숫자, 연산자 >}, n)
  • i번째 알파벳을 사용하지 않는 경우 solve(i, cnt+1, password+1, {필요 입력값들 < alpha, 숫자, 연산자 >}, n)
  • 로또
    go(a,index, cnt)
    a: 입력으로 주어지는 수
    index: 선택할지 말지 결정해야 하는 인덱스
    cnt: 현재까지 포함한 수의 개수

불가능한 경우) index == len(a)
정답을 찾은 경우) cnt == 6
다음 경우)

  • index 번째를 선택, solve(i+1, cnt+1,-, {필요 입력값들 < -, -, - >}, 6)
  • index 번째를 선택하지 않음, solve(i, cnt+1, -, {필요 입력값들 < -, -, - >}, 6)
  • 부분 집합의 합
    go(index,sum)
    index:부분집합에 포함할지 말지 결정해야 하는 인덱스
    sum: 현재까지 부분집합의 합

불가능한 경우) index == n && sum != m
정답을 찾은 경우) index==n && sum == m
다음 경우)

  • index번째를 부분집합에 추가:solve(i+1, cnt+1, sum, {필요 입력값들 < -, -, - >}, -)
  • index번째를 부분집합에 추가하지 않음 : solve(i, cnt+1, sum, {필요 입력값들 < -, -, - >}, -)
  • 퇴사
    go(day,sum)
    day일이 되었다. day일에 있는 상담을 할지 말지 결정해야 한다.
    지금까지 얻은 수익은 sum이다

불가능한 경우) day==n
정답을 찾은 경우) day > n
다음 경우)

  • 상담을 한다 : solve(i+1, cnt+1, sum, {필요 입력값들 < -, -, - >}, -)
  • 상담을 하지 않는다 : solve(i, cnt+1, sum, {필요 입력값들 < -, -, - >}, -)
  • 연산자 끼워넣기
    go(a,index,cur,plus,minus,mul,div)
    a: 입력으로 주어진 수열
    index: 현재 계산해야 하는 인덱스
    cur: index-1 번째 까지 계산한 결과
    plus,minux,mul,div : 사용할 수 있는 연산자의 개수

불가능한 경우)
정답을 찾은 경우) index==n
다음 경우)

    • 사용, : go(cur+1,cnt+1,sum, +a, plus-1, minux, mul, div, goal)
    • 사용, : go(cur+1,cnt+1,sum, -a, plus, minux-1, mul, div, goal)
    • 사용, : go(cur+1,cnt+1,sum, *a, plus, minux, mul-1, div, goal)
  • /사용, : go(cur+1,cnt+1,sum, /a, plus, minux, mul, div-1, goal)

이전 순열

def prev_permutation(array):
inverse_point = len(array)-2

while inverse_point >= 0 and array[inverse_point] <= array[inverse_point + 1]:
    inverse_point -= 1
    
if inverse_point < 0:
    return [-1]

for i in reversed(range(inverse_point,len(array))):
    if array[i] < array[inverse_point]:
        array[i], array[inverse_point] = array[inverse_point], array[i]
        break

array[inverse_point+1:] = sorted(array[inverse_point + 1:],reverse=True)

return array

cnt=int(input())
a=list(map(int,input().split()))
print(*prev_permutation(a))

3055

from collections import deque
dx = [0,0,1,-1]
dy = [1,-1,0,0]
n,m = map(int,input().split())
a = [input() for _ in range(n)]
water = [[-1]*m for _ in range(n)]
dist = [[-1]m for _ in range(n)]
q = deque()
for i in range(n):
for j in range(m):
if a[i][j] == '
':
q.append((i,j))
water[i][j] = 0
elif a[i][j] == 'S':
sx,sy = i,j
elif a[i][j] == 'D':
ex,ey = i,j
while q:
x,y = q.popleft()
for k in range(4):
nx,ny = x+dx[k], y+dy[k]
if 0 <= nx < n and 0 <= ny < m:
if water[nx][ny] != -1:
continue
if a[nx][ny] in 'XD':
continue
water[nx][ny] = water[x][y] + 1
q.append((nx,ny))

q.append((sx,sy))
dist[sx][sy] = 0
while q:
x,y= q.popleft()
for k in range(4):
nx,ny = x+dx[k],y+dy[k]
if 0 <= nx < n and 0 <= ny < m:
if dist[nx][ny] != -1:
continue
if a[nx][ny] == 'X':
continue
if water[nx][ny] != -1 and dist[x][y]+1 >= water[nx][ny]:
continue
dist[nx][ny] = dist[x][y]+1
q.append((nx,ny))

if dist[ex][ey] == -1:
print('KAKTUS')
else:
print(dist[ex][ey])

https://www.acmicpc.net/problem/10820

coding: utf-8

import sys
results = []
while True:
try:
result = [0]*4
line = input()
for c in line:
if c.islower() == True:
result[0] += 1
elif c.isupper() == True:
result[1] += 1
elif c.isdigit() == True :
result[2] += 1
else:
result[3] += 1
results.append(result)
except EOFError:
break

for result in results:
result = list(map(str, result))
print(" ".join(result))

미로탐색,2178

-- coding: utf-8 --

"""
Created on Fri Jan 10 13:40:52 2020

@author: yuseungwoo
"""

N,M=map(int,input().split())
miro=[list(map(int,list(input()))) for i in range(N)]
visit=[ [0] * M for i in range(N)]

dn=[0,-1,0,1]
dm=[-1,0,1,0]

def bfs(n_idx,m_idx):
visit[n_idx][m_idx]=1
queue=[]
queue.append([n_idx,m_idx])

while queue:
    
    sub_n,sub_m=queue.pop(0)
    
    for idx in range(4):
        
        if 0<= sub_n+dn[idx]<=N-1 and 0<=sub_m+dm[idx]<=M-1 and visit[sub_n+dn[idx]][sub_m+dm[idx]]==0 and miro[sub_n+dn[idx]][sub_m+dm[idx]]:
           
            visit[sub_n+dn[idx]][sub_m+dm[idx]] = visit[sub_n][sub_m]+1
            queue.append([sub_n+dn[idx],sub_m+dm[idx]])
            
            if sub_n+dn[idx]==N-1 and sub_m+dm[idx]==M-1:
                return 

for n_idx in range(N):
for m_idx in range(M):
if miro[n_idx][m_idx] and visit[n_idx][m_idx]==0:
bfs(n_idx,m_idx)

print(visit[N-1][M-1])

인접리스트 vs 인접배열 ( 그래프 표현)

인접성 리스트 :

a, b, c, d, e, f, g, h = range(8) 
N = [ 
 {b:2, c:1, d:3, e:9, f:4},    # a 
 {c:4, e:3},                   # b 
 {d:8},                        # c 
 {e:7},                        # d 
 {f:5},                        # e 
 {c:2, g:2, h:2},              # f 
 {f:1, h:6},                   # g 
 {f:9, g:8}                    # h 

]
인접성 매트릭스의 경우 :

a, b, c, d, e, f, g, h = range(8) 
_ = float('inf') 
#     a b c d e f g h
W = [[0,2,1,3,9,4,_,_], # a 
    [_,0,4,_,3,_,_,_], # b 
    [_,_,0,8,_,_,_,_], # c 
    [_,_,_,0,7,_,_,_], # d 
    [_,_,_,_,0,5,_,_], # e 
    [_,_,2,_,_,0,2,2], # f 
    [_,_,_,_,_,1,0,6], # g 
    [_,_,_,_,_,9,8,0]] # h

1707, 백준

-- coding: utf-8 --

"""
Created on Fri Jan 3 13:57:19 2020

@author: yuseungwoo
"""

import sys

global graph
global visit

def bfs(start):
queue=[]

queue.append(start)
visit[start] = 1
while queue:
    node=queue.pop(0)
    for i_start in graph[node]:
        if visit[i_start] == 0:
            visit[i_start] = visit[start] * -1
            queue = queue + graph[i_start]

testcase = int(input())
ans = ["NO"] * testcase

for k in range(testcase):
v, e = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(v+1)]
visit= [0] * (v+1)

for _ in range(e):
    v1, v2 = map(int, sys.stdin.readline().split())
    graph[v1].append(v2)
    graph[v2].append(v1)
  
bre=0 
    
for i in range(1, v+1):
    if(visit[i] == 0):
        bfs(i)
tmp=1        
for i in range(1, v+1):
    tmp = tmp * visit[i]
    
if (v) % 2 == 0 and tmp == 1:
    ans[k] = "YES"
if (v) % 2 == 1 and tmp == -1:
    ans[k] = "YES"        

for k in range(testcase):
print(ans[k])

https://www.acmicpc.net/problem/1406

import sys

s=sys.stdin.readline().rstrip()

lst=list(s);rst=[]
k = int(sys.stdin.readline().rstrip())
for i in range(0,k):
cmd = sys.stdin.readline().rstrip()
if cmd[0]=='L' and len(lst):
rst.append(lst.pop())
elif cmd[0]=='D' and len(rst):
lst.append(rst.pop())
elif cmd[0]=='B' and len(lst):
lst.pop()
else:
cmd=cmd.split()
if(len(cmd)==2):
lst.append(cmd[1])
ret = ''.join(lst)
for v in rst[::-1]:
ret+=v
print(ret)

재귀함수 코드 정리

  • 백준 1759번

-- coding: utf-8 --

def check(alpha):
vowel="aeiou"
vowel_cnt=0
consonant_cnt=0

for i in alpha:
    if i in vowel:
        vowel_cnt = vowel_cnt + 1
    else:
        consonant_cnt = consonant_cnt + 1 
        
if vowel_cnt >= 1 and consonant_cnt >= 2:
    return True
else:
    return False

def solve(index, password_length, ref, alpha):

if len(alpha) == password_length:
    if check(alpha)
        print(alpha)
        return

if index == len(ref):
    return 

solve(index+1, password_length, ref, alpha + ref[index])
solve(index+1, password_length, ref, alpha)

n,m=map(int,input().split())
ref=sorted(list(map(str,input().split())))

solve(0,n,ref,"")

https://www.acmicpc.net/problem/10809

chk_list=[-1] * 26
alphaList = [chr(c) for c in range(ord('a'), ord('z')+1)]

a=input()

for i in range(len(alphaList)):
chk_list[i]=a.find(alphaList[i])

for i in chk_list:
print(i,end=' ')

프로그래머스,,hash 1번 문제

import collections

def solution(participant, completion):
answer = collections.Counter(participant) - collections.Counter(completion)
return list(answer.keys())[0]

recursive

-- coding: utf-8 --

import time
start = time.time() # 시작 시간 저장

def f(n):
if n<=1:
return 1
else:
return min(f(n-1)+1,f(n-2)+1,f(n-3)+1)

print(f(20))

print("time :", time.time() - start)

1697

-- coding: utf-8 --

"""
Created on Sat Jan 11 21:45:15 2020

@author: YSW
"""

MAX=100001
N,K=map(int,input().split())
visit=[-1]*int(MAX)
queue=[N]
visit[N]=0

while queue:

node=queue.pop(0)

if node == K:
    print(visit[node])
    break

for i_node in [node-1, node+1, 2*node]:
    if 0<=i_node<MAX and visit[i_node]==-1:
        visit[i_node]=visit[node] + 1
        queue.append(i_node)

프로그래머스, 야구게임

https://geonlee.tistory.com/116

from itertools import permutations

def check_score(question, candidate, s, b):
strike = 0
for i in range(len(question)):
if question[i] == candidate[i]:
strike += 1
if s != strike:
return False
ball = len(set(question) & set(candidate))-strike
if b != ball:
return False
return True

def solution(baseball):
lst = list(permutations([1,2,3,4,5,6,7,8,9], 3))
for i in baseball:
for item in lst[:]:
if not check_score([int(i) for i in list(str(i[0]))], item, i[1], i[2]):
lst.remove(item)
return len(lst)

13549

-- coding: utf-8 --

"""
Created on Sun Jan 12 14:25:53 2020

@author: YSW
"""

n,k = map(int,input().split())
q = [n]
v = [-1 for i in range(100001)]
v[n] = 0
while q:
p = q.pop(0)
if p == k:
print(v[p])
break
if p2 <= 100000 and v[p2] == -1:
v[p2]=v[p]
q.append(p
2)
if 0 <= p-1 and v[p-1] == -1:
v[p-1]=v[p] + 1
q.append(p-1)
if p+1 <= 100000 and v[p+1] == -1:
v[p+1]=v[p] + 1
q.append(p+1)

Valid_1) dfs와 bfs 을 이용한 구현

https://itholic.github.io/python-bfs-dfs/

graph={
'A':['B','C'],
'B':['A'],
'C':['D','E'],
'D':['C'],
'E':['C']
}

def bfs(graph,start_node):
visit=[]
queue=[]

queue.append(start_node)

while queue:
    node = queue.pop(0)
    if node not in visit:
        visit.append(node)
        queue.extend(graph[node])
        
return visit

def dfs(graph,start_node):
visit=[]
stack=[]

stack.append(start_node)
while stack:
    node=stack.pop()
    if node not in visit:
        visit.append(node)
        stack.extend(graph[node])
return visit

print(dfs(graph,'A'))

백준, 퇴사 알고리즘

-- coding: utf-8 --

"""
Created on Tue Dec 31 11:31:08 2019

@author: YSW
"""

def solve(goal_max, ref_day, copy_day, ref_pay, copy_pay):

if copy_day == goal_max:
    return copy_pay
if copy_day > goal_max:
    return 0

include=0 
exclude=0

include=solve(goal_max, ref_day, copy_day + ref_day[copy_day], ref_pay, copy_pay + ref_pay[copy_day])
exclude=solve(goal_max, ref_day, copy_day + 1 , ref_pay, copy_pay)

return max(include,exclude)

ref_day=[0]
ref_pay=[0]

goal_max=int(input())
for _ in range(1,goal_max+1):
day,pay=map(int, input().split())
ref_day.append(day)
ref_pay.append(pay)

print(solve(goal_max+1,ref_day,1,ref_pay,0))

dp

-- coding: utf-8 --

import time
start = time.time() # 시작 시간 저장

n=20

global dp

dp=[-1]*2001
def f(n):

print("hellow world")

if n<=1: 
    return 1
elif dp[n] == -1:
    dp[n]=min(f(n-1)+1,f(n-2)+1,f(n-3)+1)
    return dp[n]
else:
    return dp[n]

print(f(n))

print("time :", time.time() - start)

https://www.acmicpc.net/submit/9012/15940182

import sys

def isValid(s):

cnt = 0
for x in s:
    if x == '(':
        cnt += 1
    else:
        cnt -= 1
    if cnt < 0:
        return "NO"
if cnt == 0:
    return "YES"
else:
    return "NO"

n = int(input())

for i in range(n):
print (isValid(sys.stdin.readline().rstrip()))

1261

from collections import deque
dx,dy=[0,0,1,-1],[1,-1,0,0]
m,n=map(int,input().split())
D=[[*input()] for _ in range(n)]
C=[[-1]*m for _ in range(n)]
q=deque([[0,0]]);C[0][0]=0
while q:
x,y=q.popleft()
for i in range(4):
nx,ny=x+dx[i],y+dy[i]
if 0<=nx<n and 0<=ny<m and C[nx][ny]==-1:
if D[nx][ny]=='0':C[nx][ny]=C[x][y];q.appendleft([nx,ny])
else:C[nx][ny]=C[x][y]+1;q.append([nx,ny])
print(C[n-1][m-1])

백준 이분그래프

https://www.acmicpc.net/source/1550472
https://www.acmicpc.net/source/15504725

-- coding: utf-8 --

"""
Created on Fri Jan 3 13:57:19 2020

@author: yuseungwoo
"""
import sys

global visit
global graph

def bfs(start):

queue=[]
queue.append(start)
visit[start]=1

while queue:
    node=queue.pop(0)
    for i_start in graph[node]:
        if visit[i_start]==0:
            visit[i_start]=visit[node] * -1
            queue.append(i_start)
        elif visit[i_start]==visit[node]:
            return False   
return True

proble_cnt=int(input())
ans=[True]*proble_cnt
for pro_idx in range(proble_cnt):

n,v=map(int,sys.stdin.readline().split())
graph=[[] for _ in range(n+1)]
visit=[0 for _ in range(n+1)]

for _ in range(v):
    col,row=map(int,sys.stdin.readline().split())
    graph[col].append(row)
    graph[row].append(col)

for node in range(1,n+1):
    if visit[node] == 0:
        if not bfs(node):
            ans[pro_idx] = False
            break

for pro_idx in ans:
if pro_idx == True:
print("YES")
elif pro_idx == False:
print("NO")

다음 순열

def next_permutation(a):
i=len(a)-1

while (i>0 and a[i-1] > a[i]):
    i=i-1

if( i <= 0 ) :
    return [-1][0]

j=len(a) - 1

while (True):
    if a[i-1] < a[j]:
        a[j],a[i-1] = a[i-1],a[j]
        break
    else:
        j = j-1

before_a=list(a[:i])
after=list(sorted(a[i:]))
before_a.extend(after)

return before_a

print(next_permutation([3,2,1]))

Recursive, edit-distance

def LD(s, t):
if s == "":
return len(t)
if t == "":
return len(s)
if s[-1] == t[-1]:
cost = 0
else:
cost = 1

res = min([LD(s[:-1], t)+1,  #Python을 기준으로, Peithen에 deletion이 있다고 가정 
           LD(s, t[:-1])+1, #Python을 기준으로,  Peithen에 insertion이있다고 가정, 
           LD(s[:-1], t[:-1]) + cost]) # 인식결과 같거나 틀리거나, 둘중에 하나가 발생한다고 가정, 

return res

print(LD("Python", "Peithen"))

dfs,bfs 1260 백준

-- coding: utf-8 --

"""
Created on Sat Jan 4 14:18:10 2020

@author: YSW
"""

#dfs bfs

global graph

def dfs(i):

stack=[]
visit=[]

stack.append(i)

while stack:
    node=stack.pop()
    if node not in visit:
        visit.append(node)
        stack = stack + graph[node]
return visit

def bfs(i):

queue=[]
visit=[]

queue.append(i)

while queue:
    node=queue.pop(0)
    if node not in visit:
        visit.append(node)
        queue = queue + graph[node]
return visit

n,v,start_node=map(int,input().split())

graph=[[] for _ in range(n+1)]

for _ in range(v):
col,row=map(int,input().split())
graph[col].append(row)
graph[row].append(col)

for i in range(n+1):
graph[i][:]=sorted(graph[i][:],reverse=True)

print(*dfs(start_node))

for i in range(n+1):
graph[i][:]=sorted(graph[i][:])

print(*bfs(start_node))

Valid_2 dfs bfs 구현 (인접 배열)

n, m, v = map(int, input().split())
graph = [[0 for _ in range(n+1)] for _ in range(n+1)]

def dfs(graph, start_node):

visit=[]
stack=[]

stack.append(start_node)
while stack:
    node=stack.pop()

    if node not in visit:
        visit.append(node)
        stack += sorted(list(set([i for i, n in enumerate(graph[node][:]) if n == 1]) - set(visit)),reverse = True)

return visit

def bfs(graph, start_node):

visit=[]
stack=[]

stack.append(start_node)
while stack:
    node=stack.pop(0)
    if node not in visit:
        visit.append(node)
        stack.extend((i for i, n in enumerate(graph[node][:]) if n == 1))
return visit

for _ in range(m):
x, y =map(int, input().split())
graph[x][y] = 1
graph[y][x] = 1

#print(dfs(graph,v))
#print(bfs(graph,v))

for i in dfs(graph, v):
print(i, end=" ")
print()
for j in bfs(graph, v):
print(j, end= " ")

백준 - 부분집합의 합,1182

def solve(index, goal_sum, ref, copy):

if index == len(ref):
    if sum(copy)==goal_sum:
        #print(*copy)
        return 1
    return 0    

cnt=0

copy.append(ref[index])
cnt = cnt + solve(index+1,goal_sum,ref,copy)
copy.pop()
cnt = cnt + solve(index+1,goal_sum,ref,copy)	

return cnt

empty=list()
m,n=map(int,input().split())
in_list=list(map(int,input().split()))
result=0
if m==len(in_list):
if n == 0:
result=solve(0,n,in_list,empty)-1 # 공집합 제외
else:
result=solve(0,n,in_list,empty)
print(result)

2206

https://www.acmicpc.net/source/15461146

from collections import deque

N, M = map(int, input().split())
data = [list(input()) for _ in range(N)]
dist = [[[0, 0] for _ in range(M)] for _ in range(N)]
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

def bfs():
q = deque()
q.append((0, 0, 0))
dist[0][0][0] = 1
while q:
y, x, w = q.popleft()
if y == N-1 and x == M-1:
return dist[y][x][w]
for i in range(4):
ny, nx = y+dy[i], x+dx[i]
if ny < 0 or ny >= N or nx < 0 or nx >= M:
continue
if dist[ny][nx][w]:
continue
if data[ny][nx] == '0':
dist[ny][nx][w] = dist[y][x][w] + 1
q.append((ny, nx, w))
if data[ny][nx] == '1' and w == 0:
dist[ny][nx][1] = dist[y][x][w] + 1
q.append((ny, nx, 1))
return -1

print(bfs())

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.