๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐‘†๐‘ข๐‘›๐‘ โ„Ž๐‘–๐‘›๐‘’ ๐‘Ž๐‘“๐‘ก๐‘’๐‘Ÿ ๐‘Ÿ๐‘Ž๐‘–๐‘›โœง

[Python] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ตฌ๋ช…๋ณดํŠธ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋„คํŠธ์›Œํฌ ๋ณธ๋ฌธ

๐—ฃ๐—ฟ๐—ผ๐—ด๐—ฟ๐—ฎ๐—บ๐—บ๐—ถ๐—ป๐—ด๐Ÿ’ป/[๐๐ฒ๐ญ๐ก๐จ๐ง] ๐€๐ฅ๐ ๐จ๐ซ๐ข๐ญ๐ก๐ฆ

[Python] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ตฌ๋ช…๋ณดํŠธ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋„คํŠธ์›Œํฌ

๐ŸคRyusun๐Ÿค 2023. 9. 20. 00:55

๊ตฌ๋ช…๋ณดํŠธ

#ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ตฌ๋ช…๋ณดํŠธ

def solution(people, limit):
    cnt = 0
    people = deque(sorted(people))
    while people:
        person = people.pop()

        if people and person + people[0] <= limit:
            people.popleft()
            
        cnt += 1

    return cnt

ํ + ๊ทธ๋ฆฌ๋””๋กœ ํ•ด๊ฒฐ

 

๋„คํŠธ์›Œํฌ

from collections import deque

def solution(n, computers):
    visited = [False] * (n+1)
    graph = [[] for _ in range(n + 1)]
    for i in range(n):
        for j in range(n):
            if i != j and computers[i][j] == 1:
                graph[i].append(j)
                graph[j].append(i)

    cnt = 0
    for i in range(n):
        if not visited[i]:
            cnt += bfs(graph, visited, i)
    return cnt

def bfs(graph,visited, start_node):
    queue = deque()
    queue.append(start_node)
    visited[start_node] = True
    while queue:
        current_node = queue.popleft()
        for next_node in graph[current_node]:
            if not visited[next_node]:
                queue.append(next_node)
                visited[next_node] = True
                
    return 1

print(solution(3,  [[1, 1, 0], [1, 1, 0], [0, 0, 1]]))

์ฒ˜์Œ์—๋Š” ์ •๋‹ต์œผ๋กœ ์ „์ฒด visited๊ฐœ์ˆ˜๋ฅผ ์…Œ๋Š”๋ฐ ์‹คํŒจ...ใ… ใ… 

๋งŒ์•ฝ ์ปดํ“จํ„ฐ ๊ฐœ์ˆ˜๊ฐ€ 5๊ฐœ์ด๊ณ  3๊ฐœ 2๊ฐœ๋กœ ์—ฐ๊ฒฐ๋ผ์žˆ์œผ๋ฉด ๋„คํŠธ์›Œํฌ ๊ฐœ์ˆ˜๋Š” ์ด 2๊ฐœ์ธ๋ฐ ์ด ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐ์น˜ ๋ชปํ•ด์„œ ์ข€ ํ—ค๋งธ๋‹คใ… ใ…  ์ „์ฒด ์ปดํ“จํ„ฐ๋ฅผ ๋Œ๋ฉด์„œ ๋งŒ์•ฝ ๋ฐฉ๋ฌธ์„ ์•ˆํ–ˆ์œผ๋ฉด bfs()๋Œ๊ณ  ๋ฐ˜ํ™˜๊ฐ’์„ 1๋กœ ํ•ด์„œ ์ด ๋„คํŠธ์›Œํฌ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์คฌ๋‹ค.