ํฐ์คํ ๋ฆฌ ๋ทฐ
๐ฉ๐ป๐ป ๋ฌธ์
โ๐ป ํ์ด
๐จ Go
// https://www.acmicpc.net/problem/1260
package main
import (
"bufio"
"fmt"
"os"
)
var (
graph [][]int
visited []bool
writer *bufio.Writer
)
func main() {
reader := bufio.NewReader(os.Stdin)
writer = bufio.NewWriter(os.Stdout)
defer writer.Flush()
var n, m, v int
fmt.Fscanln(reader, &n, &m, &v)
graph = make([][]int, n+1)
for i := range graph {
graph[i] = make([]int, n+1)
}
visited = make([]bool, n+1)
for i := 0; i < m; i++ {
var vertex1, vertex2 int
fmt.Fscanln(reader, &vertex1, &vertex2)
graph[vertex1][vertex2] = 1
graph[vertex2][vertex1] = 1
}
dfs(v)
fmt.Fprintln(writer, "")
resetVisited()
bfs(v)
fmt.Fprintln(writer, "")
}
func dfs(v int) {
visited[v] = true // dfs์ ๋ค์ด์ค๋ฉด ๋ฐฉ๋ฌธํ๋ค๊ณ ํ๋จ
fmt.Fprintf(writer, "%d ", v)
for i := 0; i < len(graph[v]); i++ {
if graph[v][i] == 1 && !visited[i] { // ์ฐ๊ฒฐ๋์ด ์๊ณ ๋ฐฉ๋ฌธํ์ง ์์ ๊ฒฝ์ฐ
dfs(i) // ์ฌ๊ทํจ์ ํธ์ถ
}
}
}
func bfs(v int) {
visited[v] = true
queue := []int{v}
for len(queue) != 0 {
front := queue[0]
fmt.Fprintf(writer, "%d ", front)
queue = queue[1:]
for i := 0; i < len(graph[v]); i++ {
if graph[front][i] == 1 && !visited[i] { // ์ฐ๊ฒฐ๋์ด ์๊ณ ๋ฐฉ๋ฌธํ์ง ์์ ๊ฒฝ์ฐ
visited[i] = true // ๋ฐฉ๋ฌธ ํ์
queue = append(queue, i) // ํ์ ์ฝ์
}
}
}
}
func resetVisited() {
for i := 0; i < len(visited); i++ {
visited[i] = false
}
}
๐จ Python3
# https://www.acmicpc.net/problem/1260
import sys
graph = []
visited = []
def dfs(v):
visited[v] = True
print("{} ".format(v), end="")
for i in range(len(graph[v])):
if graph[v][i] == 1 and not visited[i]:
dfs(i)
def bfs(v):
visited[v] = True
queue = [v]
while (len(queue) != 0):
front = queue.pop(0)
print("{} ".format(front), end="")
for i in range(len(graph[v])):
if graph[front][i] == 1 and not visited[i]:
visited[i] = True
queue.append(i)
def reset_visited():
for i in range(len(visited)):
visited[i] = False
if __name__ == "__main__":
n, m, v = map(int, sys.stdin.readline().split())
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(m):
vertex1, vertex2 = map(int, sys.stdin.readline().split())
graph[vertex1][vertex2] = 1
graph[vertex2][vertex1] = 1
dfs(v)
print()
reset_visited()
bfs(v)
print()
728x90
'dev > algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ / 7785๋ฒ / ํ์ฌ์ ์๋ ์ฌ๋ [Go][Python3] (0) | 2020.12.07 |
---|---|
BOJ / 2606๋ฒ / ๋ฐ์ด๋ฌ์ค [Go][Python3] (0) | 2020.12.06 |
BOJ / 7596๋ฒ / MP3 Songs [Go][Python3] (0) | 2020.12.04 |
BOJ / 2204๋ฒ / ๋๋น์ ๋๋ ์ฆ ํ ์คํธ [Go][Python3] (0) | 2020.12.03 |
BOJ / 20291๋ฒ / ํ์ผ ์ ๋ฆฌ [Go][Python3] (0) | 2020.12.02 |
๋๊ธ
๊ธ ๋ณด๊ดํจ
์ต๊ทผ์ ๋ฌ๋ฆฐ ๋๊ธ
TAG
- ์ด๋ถํ์
- BOJ
- ์คํ
- go
- ํด์๋งต
- ๋ฐฑ์ค
- Golang
- ๋งฅ๋ถํ๋ก
- ํ
- ๋ธ๋ฃจํธํฌ์ค
- BFS
- ํ๋ก์ด๋์์ฌ
- ์๊ณ ๋ฆฌ์ฆ
- java
- ๋ชฝ๊ณ ๋๋น
- python3
- baekjoon
- ๋งฅ๋ถ ์ ๊ทธ๋ ์ด๋
- ์๊ฐ๊ต์ฒด
- ๋ถํ ์ ๋ณต
- MongoDB
- ballet
- Algorithm
- ๋งฅ๋ถ
- ๋ฐ๋
- AWS
- Macbook pro 2012 mid 13
- ์๋ฐ
- dfs
- dp
- Total
- Today
- Yesterday