ํฐ์คํ ๋ฆฌ ๋ทฐ
๐ฉ๐ป๐ป ๋ฌธ์
โ๐ป ํ์ด
๐จ 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
- go
- java
- python3
- ์ด๋ถํ์
- ํ
- Macbook pro 2012 mid 13
- baekjoon
- ํ๋ก์ด๋์์ฌ
- ๋ธ๋ฃจํธํฌ์ค
- Algorithm
- ๋งฅ๋ถ
- AWS
- Golang
- ๋ฐ๋
- ๋ชฝ๊ณ ๋๋น
- ๋ถํ ์ ๋ณต
- BFS
- ๋ฐฑ์ค
- dp
- ์คํ
- dfs
- ์๋ฐ
- ํด์๋งต
- ๋งฅ๋ถ ์ ๊ทธ๋ ์ด๋
- ๋งฅ๋ถํ๋ก
- ์๊ฐ๊ต์ฒด
- ballet
- BOJ
- MongoDB
- ์๊ณ ๋ฆฌ์ฆ
- Total
- Today
- Yesterday