코테

MUUU·2022년 12월 25일
0

코딩테스트

목록 보기
8/8

프로그래머스 lv.1


**각 숫자를 더한 값


def solution(n):
    answer = 0

    a=[int(i) for i in str(n)]
    answer=sum(a)

    return answer

**배수/약수 값. 예외일때

def solution(arr, divisor):
    answer = []
    a=[i for i in arr if i % divisor ==0] ## 배수는 % 0 으로 나누어 떨어지는가 
    answer=sorted(a)
    
    if len(answer)==0: # null이 아니라 len()==0
        answer=[-1]

    return answer

level 2 너무 어려워서 bfs/dfs 먼저 (코드업)

코드업 BFS/DFS

1.코드업 배수(hard)

from collections import deque

def bfs(n,s):
  q= deque([s]) # 리스트에 담아서
  
  
  
  while q:
      t= q.popleft() # 1, 10, 11,, 순서대로 증가할 것 
  
      if t>=2**64:
          return 0
      elif t%n==0: # 배수이다
          return t
      
      q.append(t*10) # 1, 10, 100, 110,  1000
      q.append(t*10+1) # null(popleft), 11, 101, 111
  
n=int(input())
print(bfs(n,1)) # 1로 시작하는 자연수

2. 캔디팡(bfs)



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

from collections import deque

dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]    # 상하좌우

def bfs(x, y, board, visited):
    queue = deque()
    queue.append((x, y))
    visited[x][y] = True    # 방문 처리

    color = board[x][y]    # 현재 칸의 색상
    count = 1    # 연속된 같은 색의 칸 개수

    # 큐가 빌 때까지 반복
    while queue:
        x, y = queue.popleft()

        # 현재 칸에서 상하좌우 확인
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]

            # 보드 넘어서면 무시하기
            if nx < 0 or nx >= 7 or ny < 0 or ny >= 7:
                continue

            # 칸의 색상이 동일하고 방문한 적 없으면 재귀 (그 칸을 기준으로 다시 상하좌우 확인)
            if board[nx][ny] == color and not visited[nx][ny]:
                queue.append((nx, ny))
                visited[nx][ny] = True    # 방문처리
                count += 1

    # 색상이 같은 부분이 3개 이상이면
    if count >= 3:
        return True
    else:
        return False

visited = [[False for _ in range(7) ] for _ in range(7)]    # 방문 여부
res = 0    # 터지는 영역의 개수

for i in range(7):
    for j in range(7):
        if not visited[i][j]:
            if bfs(i, j, board, visited):
                res += 1

print(res)

3. 호수의 수 구하기(bfs)

**대각선 주의


12 10
L . . . . . . . . L . .
. L . . . . . . . L L .
L L . . . . . . . . L .
. L . . . . . . . . . L
. . L . . . . . . . . L
. . . . . . L . . . . .
. . . . . L . L . . . .
. . . . L . L . L . . .
. . . . . L . L . . . .
. . . . . . L . . . . L

#3. 방향 벡터 (대각선만 유의하면 될듯)
global dx, dy
dx=[0,0,1,-1,1,-1,1,-1]
dy=[1,-1,0,0,1,-1,-1,1]


from collections import deque

def bfs(x,y):
    queue=deque()
    queue.append([x,y])
    check[x][y]=1

    while queue:
        x,y=queue.popleft()

        for i in range(8):
            nx,ny=x+dx[i],y+dy[i]
            if 0<=nx and nx<h and 0<=ny and ny<w:
                if lack[nx][ny]=='L' and check[nx][ny]==0:
                    check[nx][ny]=1
                    queue.append([nx,ny])




#1. 지도의 너비, 높이 w,h
global w,h
w,h=map(int,input().split())


#2. 호수 지도 생성
global lack
lack=[]

for i in range(h):
    lack.append(list(map(str,input().split())))


#3. 방향 벡터 (대각선까지 추가)
global dx, dy
dx=[0,0,1,-1,1,-1,1,-1]
dy=[1,-1,0,0,1,-1,-1,1]


#4. bfs 탐색
count=0

global check
check=[[0 for x in range(w)] for y in range(h)]

for i in range(h):
    for j in range(w):
        # 호수인데 아직 탐색이 안된 곳
        if lack[i][j]=='L' and check[i][j]==0:
            bfs(i,j)
            count+=1


print(count)

4.위상정렬(bfs)

https://velog.io/@younge/Python-%EA%B7%B8%EB%9E%98%ED%94%84-%EC%9C%84%EC%83%81-%EC%A0%95%EB%A0%AC-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98

profile
데이터분석

0개의 댓글