ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

2644๋ฒˆ: ์ดŒ์ˆ˜๊ณ„์‚ฐ

์‚ฌ๋žŒ๋“ค์€ 1, 2, 3, …, n (1≤n≤100)์˜ ์—ฐ์†๋œ ๋ฒˆํ˜ธ๋กœ ๊ฐ๊ฐ ํ‘œ์‹œ๋œ๋‹ค. ์ž…๋ ฅ ํŒŒ์ผ์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ „์ฒด ์‚ฌ๋žŒ์˜ ์ˆ˜ n์ด ์ฃผ์–ด์ง€๊ณ , ๋‘˜์งธ ์ค„์—๋Š” ์ดŒ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด์•ผ ํ•˜๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ์‚ฌ๋žŒ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

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

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

var (
	graph  [][]int
	writer *bufio.Writer
	answer int
)

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

	var n, from, to, m int
	fmt.Fscanln(reader, &n)
	fmt.Fscanln(reader, &from, &to)
	fmt.Fscanln(reader, &m)
	graph = make([][]int, n+1)
	for i := 0; i < len(graph); i++ {
		graph[i] = make([]int, n+1)
	}
	for i := 0; i < m; i++ {
		var parent, child int
		fmt.Fscanln(reader, &parent, &child)
		graph[parent][child] = 1
		graph[child][parent] = 1
	}

	dfs(from, to, 0, 0)
	if answer == 0 {
		answer = -1
	}
	fmt.Fprintln(writer, answer)
}

func dfs(from, to, prev, count int) {
	if from == to {
		answer = count
		return
	}
	for i := 0; i < len(graph); i++ {
		if graph[from][i] == 1 && i != prev { // ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๊ณ  ์ด์ „ ๋ฐฉ๋ฌธํ•œ ์ ์ด ์•„๋‹Œ ๊ฒฝ์šฐ
			dfs(i, to, from, count+1) // ์žฌ๊ท€ํ•จ์ˆ˜ ํ˜ธ์ถœ
		}
	}
	return
}

๐ŸŽจ Python3

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

graph = []
answer = 0

def dfs(person1, person2, prev, count):
    global answer
    if person1 == person2:
        answer = count
        return
    for i in range(len(graph)):
        if graph[person1][i] == 1 and i != prev:
            dfs(i, person2, person1, count+1)

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    person1, person2 = list(map(int, sys.stdin.readline().split()))
    m = int(sys.stdin.readline())
    graph = [[0 for i in range(n+1)] for j in range(n+1)]

    for i in range(m):
        parent, child = list(map(int, sys.stdin.readline().split()))
        graph[parent][child] = 1
        graph[child][parent] = 1

    dfs(person1, person2, 0, 0)
    if answer == 0:
        answer = -1
    print(answer)
728x90
๋Œ“๊ธ€