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

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

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net


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

๐ŸŽจ 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
๋Œ“๊ธ€