ํฐ์คํ ๋ฆฌ ๋ทฐ
๐ฉ๐ป๐ป ๋ฌธ์
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
'dev > algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ / 1012๋ฒ / ์ ๊ธฐ๋ ๋ฐฐ์ถ [Go][Python3] (0) | 2020.12.13 |
---|---|
BOJ / 4963๋ฒ / ์ฌ์ ๊ฐ์ [Go][Python3] (0) | 2020.12.12 |
BOJ / 10867๋ฒ / ์ค๋ณต ๋นผ๊ณ ์ ๋ ฌํ๊ธฐ [Go][Python3] (0) | 2020.12.09 |
BOJ / 1934๋ฒ / ์ต์๊ณต๋ฐฐ์ [Go][Python3] (0) | 2020.12.08 |
BOJ / 7785๋ฒ / ํ์ฌ์ ์๋ ์ฌ๋ [Go][Python3] (0) | 2020.12.07 |
๋๊ธ
๊ธ ๋ณด๊ดํจ
์ต๊ทผ์ ๋ฌ๋ฆฐ ๋๊ธ
TAG
- MongoDB
- dp
- ๋ถํ ์ ๋ณต
- ์๊ณ ๋ฆฌ์ฆ
- BOJ
- ํด์๋งต
- ๋งฅ๋ถ ์ ๊ทธ๋ ์ด๋
- BFS
- ballet
- baekjoon
- ๋ชฝ๊ณ ๋๋น
- ๋ฐ๋
- java
- ์๊ฐ๊ต์ฒด
- python3
- go
- ๋งฅ๋ถ
- ์๋ฐ
- Golang
- ์คํ
- Algorithm
- ๋ฐฑ์ค
- ์ด๋ถํ์
- AWS
- ํ
- dfs
- Macbook pro 2012 mid 13
- ๋ธ๋ฃจํธํฌ์ค
- ํ๋ก์ด๋์์ฌ
- ๋งฅ๋ถํ๋ก
- Total
- Today
- Yesterday