๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ํ”Œ๋กœ์ด๋“œ BOJ #11404

by seolhee2750 2022. 6. 23.
๋ฌธ์ œ

https://www.acmicpc.net/problem/11404

 

11404๋ฒˆ: ํ”Œ๋กœ์ด๋“œ

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ n์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜ m์ด ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„๋ถ€ํ„ฐ m+2์ค„๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฒ„์Šค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ฒ˜์Œ์—๋Š” ๊ทธ ๋ฒ„์Šค์˜ ์ถœ๋ฐœ ๋„์‹œ์˜ ๋ฒˆํ˜ธ๊ฐ€

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys
import math

n = int(sys.stdin.readline().strip())
m = int(sys.stdin.readline().strip())
INF = math.inf
table = [[INF for _ in range(n)] for _ in range(n)]

for _ in range(m):
    a, b, c = map(int, sys.stdin.readline().strip().split())
    table[a-1][b-1] = min(table[a-1][b-1], c)

for k in range(n):
    for i in range(n):
        for j in range(n):
            if i == j:
                table[i][j] = 0
            else:
                table[i][j] = min(table[i][j], table[i][k] + table[k][j])

for i in range(i):
    for j in range(j):
        if table[i][j] == INF:
            table[i][j] = 0

print('\n'.join(' '.join(map(str, i)) for i in table))

๐Ÿ‘‰ ํ”Œ๋กœ์ด๋“œ ์›Œ์…œ ๋ฌธ์ œ

  • 3์ค‘ for๋ฌธ ์ด์šฉ, k๋Š” ์ค‘๊ฐ„ ๊ฒฝ๋กœ๋ผ๊ณ  ์„ค์ •ํ•˜์—ฌ ํ”Œ๋กœ์ด๋“œ ์›Œ์…œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ–ˆ๋‹ค.
  • ์ถœ๋ฐœ ์ง€์ ๊ณผ ๋„์ฐฉ ์ง€์ ์ด ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ์—†์œผ๋ฏ€๋กœ i == j ์˜ ๊ฒฝ์šฐ 0์„ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.
  • ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ์—๋Š” ๊ธฐ์กด์˜ ๊ฐ’๊ณผ k๋ฅผ ๊ฑฐ์น  ๊ฒฝ์šฐ์˜ ๊ฐ’ ์ค‘ ๋” ์‹ผ ๊ฐ’์„ ์ฐพ์•„ ๋Œ€์ฒดํ–ˆ๋‹ค.

+ ์ด ๋ฌธ์ œ์ฒ˜๋Ÿผ ์ตœ์†Ÿ๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•ด์ฃผ์–ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, ์ฒ˜์Œ ๋ณ€์ˆ˜๋ฅผ ์–ด๋–ค ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”ํ• ์ง€ ๊ฒฐ์ •ํ•˜๊ธฐ ์–ด๋ ต๋‹ค.

์ œ์ผ ํด ๊ฒƒ์œผ๋กœ ์˜ˆ์ƒ๋˜๋Š” ์ตœ์†Ÿ๊ฐ’๋ณด๋‹ค๋Š” ๋” ํฐ ๊ฐ’์œผ๋กœ ์„ค์ •ํ•ด์ฃผ์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

ํ•˜์ง€๋งŒ ์œ„์™€ ๊ฐ™์ด math.inf ๋ฅผ ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋ฌดํ•œ๋Œ€ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ํŽธ๋ฆฌํ•˜๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ถœ๋ฐœ ์ง€์ ๊ณผ ๋„์ฐฉ ์ง€์ ์ด ๊ฐ™์€ ๊ฒฝ์šฐ๋งŒ ์ž˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌํ•ด์ฃผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ !
    ํ”Œ๋กœ์ด๋“œ ์›Œ์…œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฐ€์žฅ ๊ธฐ๋ณธ์ ์ธ ์˜ˆ์ œ์ธ ๊ฒƒ ๊ฐ™๋‹ค.

๋Œ“๊ธ€