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

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

 

11403๋ฒˆ: ๊ฒฝ๋กœ ์ฐพ๊ธฐ

๊ฐ€์ค‘์น˜ ์—†๋Š” ๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„ G๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋“  ์ •์  (i, j)์— ๋Œ€ํ•ด์„œ, i์—์„œ j๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net


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

๐ŸŽจ Go

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

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

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

	var n int
	fmt.Fscanln(reader, &n)

	var graph = make([][]int, n)
	for i := 0; i < n; i++ {
		graph[i] = make([]int, n)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Fscanf(reader, "%d ", &graph[i][j])
		}
	}

	result := floydWarshall(graph)
	for i := 0; i < len(result); i++ {
		for j := 0; j < len(result[i]); j++ {
			fmt.Fprintf(writer, "%d ", result[i][j])
		}
		fmt.Fprintln(writer, "")
	}
}

func floydWarshall(graph [][]int) [][]int {
	for i := 0; i < len(graph); i++ { // j->i->k ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ j->k ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๊ฐฑ์‹ ํ•œ๋‹ค.
		for j := 0; j < len(graph); j++ {
			for k := 0; k < len(graph); k++ {
				if graph[j][i] != 0 && graph[i][k] != 0 {
					graph[j][k] = 1
				}
			}
		}
	}
	return graph
}

๐ŸŽจ Python3

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

def floyd_warshall(graph):
    for i in range(len(graph)):
        for j in range(len(graph)):
            for k in range(len(graph)):
                if graph[j][i] != 0 and graph[i][k] != 0:
                    graph[j][k] = 1
    return graph

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    graph = []
    for i in range(n):
        graph.append(list(map(int, sys.stdin.readline().split())))

    result = floyd_warshall(graph)
    for i in range(n):
        for j in range(n):
            print("{} ".format(result[i][j]), end='')
        print()
728x90
๋Œ“๊ธ€