๊ทธ๋ํ
โข
๋ฐฉํฅ์ฌ๋ถ : ๋ฌดํฅ๊ทธ๋ํ(์๋ฐฉํฅ) vs ์ ํฅ๊ทธ๋ํ(๋จ๋ฐฉํฅ)
โข
๊ฐ์ค์น์ฌ๋ถ : ๋น๊ฐ์ค์น๊ทธ๋ํ vs ๊ฐ์ค์น๊ทธ๋ํ
ํ์ด์ฌ์ ๊ทธ๋ํ ๊ตฌํ ๋ฐฉ๋ฒ
1.
n*n ๋ฐฐ์ด(์ธ์ ํ๋ ฌ)
2.
๋์
๋๋ฆฌ or ๋ฐฐ์ด(์ธ์ ๋ฆฌ์คํธ)
์ด ๋ฌธ์ ๋ ๊ฐ์ค์น ๋จ๋ฐฉํฅ๊ทธ๋ํ์ด๋ค.
Code
์ธ์ ํ๋ ฌ
n, m = map(int, input().split())
graph = [[0] * (n + 1) for _ in range(n + 1)]
for _ in range(m):
i, j, w = map(int, input().split()) # ์์,๋์ฐฉ,๊ฐ์ค์น
graph[i][j] = w
for i in range(1, n + 1):
for j in range(1, n + 1):
print(graph[i][j], end=" ")
print()
"""
6 9
1 2 7
1 3 4
2 1 2
2 3 5
2 5 5
3 4 5
4 2 2
4 5 5
6 4 5
"""
0 7 4 0 0 0
2 0 5 0 5 0
0 0 0 5 0 0
0 2 0 0 5 0
0 0 0 0 0 0
0 0 0 5 0 0
Python
๋ณต์ฌ
์ธ์ ๋ฆฌ์คํธ(๋ฐฐ์ด)
# ์ธ์ ๋ฆฌ์คํธ ๋ฐฉ์ (๋ฐฐ์ด์ฌ์ฉ)
n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
i, j, w = map(int, input().split())
graph[i].append((j, w)) # (j,w) == (๋์ฐฉ๋
ธ๋, ๊ฐ์ค์น)
for i in range(len(graph)):
print(f"{i} : {graph[i]}")
"""
6 9
1 2 7
1 3 4
2 1 2
2 3 5
2 5 5
3 4 5
4 2 2
4 5 5
6 4 5
"""
0 : []
1 : [(2, 7), (3, 4)]
2 : [(1, 2), (3, 5), (5, 5)]
3 : [(4, 5)]
4 : [(2, 2), (5, 5)]
5 : []
6 : [(4, 5)]
Python
๋ณต์ฌ
์ธ์ ๋ฆฌ์คํธ(๋์ ๋๋ฆฌ)
์ ์ผ ์ข์ ๋ฐฉ์
# ์ธ์ ๋ฆฌ์คํธ ๋ฐฉ์ (๋์
๋๋ฆฌ์ฌ์ฉ)
n, m = map(int, input().split())
graph = {}
# ๋
ธ๋๊ฐ์ผ๋ก ๋์
๋๋ฆฌ์ key ์์ฑ
for i in range(1, n + 1): # 1๋ฒ๋
ธ๋๋ถํฐ n๋ฒ๊น์ง๋ก ํด์ผํ๋ฏ๋ก
graph[i] = []
# ๊ทธ๋ํ ์์ฑ
for _ in range(m):
i, j, w = map(int, input().split())
graph[i].append((j, w)) # i : ์์๋
ธ๋, j : ๋์ฐฉ๋
ธ๋, w : ๊ฐ์ค์น
# graph[i] += [(j, w)] # ๋๊ฐ์ ์ฝ๋
for i in graph.keys():
print(f"{i} : {graph[i]}")
"""
6 9
1 2 7
1 3 4
2 1 2
2 3 5
2 5 5
3 4 5
4 2 2
4 5 5
6 4 5
"""
1 : [(2, 7), (3, 4)]
2 : [(1, 2), (3, 5), (5, 5)]
3 : [(4, 5)]
4 : [(2, 2), (5, 5)]
5 : []
6 : [(4, 5)]
Python
๋ณต์ฌ
ย ์ด ๋ฐฉ์์ด ์ ์ผ ์ข์ ์ด์ ๋ ์ธ์ ๋
ธ๋๊ฐ ์๋ ๋
ธ๋๋ ์์ฑ์ ํด์ค๋ค. (5๋ฒ๋
ธ๋)
๋น์ถ์ฒ
# ์ธ์ ๋ฆฌ์คํธ ๋ฐฉ์ 2 (๋์
๋๋ฆฌ์ฌ์ฉ)
n, m = map(int, input().split())
graph = {}
for _ in range(m):
i, j, w = map(int, input().split())
graph[i] = graph.get(i, []) + [(j, w)] # append((j,w)) ๋ก ํ๋ฉด ์๋จ! append ์ ๋ฆฌํด์ None ์ด๋ฏ๋ก
# (j,w) == (๋์ฐฉ๋
ธ๋, ๊ฐ์ค์น)
for i in graph.keys():
print(f"{i} : {graph[i]}")
"""
6 9
1 2 7
1 3 4
2 1 2
2 3 5
2 5 5
3 4 5
4 2 2
4 5 5
6 4 5
"""
1 : [(2, 7), (3, 4)]
2 : [(1, 2), (3, 5), (5, 5)]
3 : [(4, 5)]
4 : [(2, 2), (5, 5)]
6 : [(4, 5)]
Python
๋ณต์ฌ
ย ๋๊ฐ์ด ๋์
๋๋ฆฌ๋ก ๊ตฌํ์ ํ์ง๋ง get() ํจ์๋ฅผ ์จ์ผํ๊ณ , ์ธ์ ๋
ธ๋๊ฐ ์๋ ๋
ธ๋ (5๋ฒ๋
ธ๋) ๋ ์์ ์์ฑ์ด ์๋ ๊ฒ์ ๋ณผ ์ ์๋ค. ๊ฐํน ์ด๊ฒ๋๋ฌธ์ ์์ธ์ฒ๋ฆฌ๋ฅผ ํด์ค์ผํ ๋๊ฐ ์์ด์ ๊ทธ๋ฅ 1๋ฒ ๋์
๋๋ฆฌ ๋ฐฉ์์ด ๋ ํธํ๋ค.