ν‹°μŠ€ν† λ¦¬ λ·°

πŸ‘©πŸ»‍πŸ’» λ¬Έμ œ

 

2606번: λ°”μ΄λŸ¬μŠ€

첫째 μ€„μ—λŠ” μ»΄ν“¨ν„°μ˜ μˆ˜κ°€ 주어진닀. μ»΄ν“¨ν„°μ˜ μˆ˜λŠ” 100 μ΄ν•˜μ΄κ³  각 μ»΄ν“¨ν„°μ—λŠ” 1번 λΆ€ν„° μ°¨λ‘€λŒ€λ‘œ λ²ˆν˜Έκ°€ 맀겨진닀. λ‘˜μ§Έ μ€„μ—λŠ” λ„€νŠΈμ›Œν¬ μƒμ—μ„œ 직접 μ—°κ²°λ˜μ–΄ μžˆλŠ” 컴퓨터 쌍의 μˆ˜κ°€ μ£Όμ–΄

www.acmicpc.net


✍🏻 ν’€μ΄

🎨 Go

// https://www.acmicpc.net/problem/2606
package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	graph   [][]int
	visited []bool
	writer  *bufio.Writer
	count   int
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n, edge int
	fmt.Fscanln(reader, &n)
	fmt.Fscanln(reader, &edge)

	graph = make([][]int, n+1)
	for i := 0; i < n+1; i++ {
		graph[i] = make([]int, n+1)
	}
	visited = make([]bool, n+1)

	for i := 0; i < edge; i++ {
		var computer1, computer2 int
		fmt.Fscanln(reader, &computer1, &computer2)
		graph[computer1][computer2] = 1
		graph[computer2][computer1] = 1
	}

	dfs(1)
	fmt.Fprintln(writer, count-1)
}

func dfs(start int) {
	visited[start] = true
	count++
	for i := 0; i < len(graph[start]); i++ {
		if graph[start][i] == 1 && !visited[i] {
			dfs(i)
		}
	}
}

🎨 Python3

# https://www.acmicpc.net/problem/2606
import sys

count = 0

def dfs(start):
    visited[start] = True
    global count
    count += 1

    for i in range(len(graph[start])):
        if graph[start][i] == 1 and not visited[i]:
            dfs(i)

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    edge = int(sys.stdin.readline())

    graph = [[0 for i in range(n+1)] for j in range(n+1)]
    visited = [False for i in range(n+1)]

    for i in range(edge):
        computer1, computer2 = list(map(int, sys.stdin.readline().split()))
        graph[computer1][computer2] = 1
        graph[computer2][computer1] = 1

    dfs(1)
    print(count-1)
728x90
λŒ“κΈ€