๐ ๋ฌธ์ ํ์ํ๊ธฐ
- ์ด์ง ํธ๋ฆฌ ๋ชจ์ ์ด์์ ๊ฐ ๋ ธ๋์ ๋๋์ ์์ด ํ ๋ง๋ฆฌ์ฉ ๋์ฌ ์๋ค.
- ์ด์์ ๋ฃจํธ ๋
ธ๋์์ ์ถ๋ฐํด ๊ฐ ๋
ธ๋๋ฅผ ๋์๋ค๋๋ฉฐ ์์ ๋ชจ์ผ๊ณ ์ ํ๋ค.
- ๊ฐ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ ๋๋ง๋ค ํด๋น ๋ ธ๋์ ์๊ณผ ๋๋๊ฐ ๋ฐ๋ผ์จ๋ค.
- ๋ชจ์ ์์ ์ ≤ ๋ชจ์ ๋๋์ ์๊ฐ ๋๋ฉด ๋๋๊ฐ ๋ชจ๋ ์์ ์ก์๋จน๋๋ค.
- info = ๊ฐ ๋
ธ๋์ ์๋ ์ ๋๋ ๋๋์ ๋ํ ์ ๋ณด๊ฐ ๋ด๊ธด ๋ฐฐ์ด
- info์ ์์๋ 0 ๋๋ 1
- 2 ≤ info์ ๊ธธ์ด ≤ 17
- info[i]๋ i๋ฒ ๋ ธ๋์ ์๋ ์ ๋๋ ๋๋์ด๋ฉฐ, info[0]์ ํญ์ 0
- edges = ์ด์ง ํธ๋ฆฌ์ ๊ฐ ๋
ธ๋๋ค์ ์ฐ๊ฒฐ ๊ด๊ณ๋ฅผ ๋ด์ 2์ฐจ์ ๋ฐฐ์ด
- edges์ ์ธ๋ก ๊ธธ์ด = info์ ๊ธธ์ด -1
- edges์ ๊ฐ๋ก ๊ธธ์ด = 2
- edges์ ๊ฐ ํ = [๋ถ๋ชจ ๋ ธ๋ ๋ฒํธ, ์์ ๋ ธ๋ ๋ฒํธ] ํํ
- ๋์ผํ ๊ฐ์ ์ ๋ํ ์ ๋ณด๊ฐ ์ค๋ณตํด์ ์ฃผ์ด์ง์ง ์์
- 0๋ฒ ๋ ธ๋๋ ํญ์ ๋ฃจํธ ๋ ธ๋
- ์ต๋ํ ๋ง์ ์์ ์์ ๋ชจ์์ ๋ฃจํธ ๋ ธ๋๋ก ๋์์ฌ ๋, ๋ช ๋ง๋ฆฌ ๋ชจ์ ์ ์๋์ง ๊ตฌํ๊ธฐ
ํ์ฌ ๋ ธ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ ธ๋์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋ ธ๋๋ก ํ๋ฒ์ฉ ์ด๋ํด์ ๊ฒฐ๊ณผ๋ฅผ ๊ฐฑ์ ํ๋ฉด์ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ํ์ํ๋, ๋ฐฑํธ๋ํน์ ์ฌ์ฉํด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ณ ์ ํ๋ค. ๋ค๋ง, ์ด๋ฏธ ์ง๋์จ ๋ ธ๋๋ก ๋ค์ ๋์๊ฐ ๋ค๋ฅธ ๋ ธ๋๋ก ์ด๋ํ ์ ์์ผ๋ฏ๋ก ์ด์ ๋ํ ์ฒ๋ฆฌ์ ์ฃผ์ํ๋ค.
๐ ์ฝ๋ ์ค๊ณํ๊ธฐ
- ์ฃผ์ด์ง info์ edges๋ฅผ ๋ฐํ์ผ๋ก ์ด์์ ๊ฐ ๋ ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ์ ์ฅํ grassland ๋ฆฌ์คํธ๋ฅผ ์์ฑํ๊ณ , ๊ฐ ๋ ธ๋ ์์๋ง๋ค [ํด๋น ๋ ธ๋์ ์ฐ๊ฒฐ๋ ๋ ธ๋๋ค]๋ฅผ ์ ์ฅํด ์ด๊ธฐํํ๋ค.
- ๋ชจ์ ์์ ์ต๋ ๋ง๋ฆฌ ์๋ฅผ ์ ์ฅํ max_sheep ๋ณ์๋ฅผ 0์ผ๋ก ์ด๊ธฐํํ๋ค.
- ํ์ฌ ๋
ธ๋์ ๋ฐฉ๋ฌธ ์ ๋ณด๋ฅผ ์ ์ฅํ visited๋ฅผ ์ด๊ธฐํํ๋ค.
- visited[i][a][b] = i๋ฒ์งธ ๋ ธ๋์ ์ a๋ง๋ฆฌ์ ๋๋ b๋ง๋ฆฌ๋ฅผ ๊ฐ์ง๊ณ ๋ฐฉ๋ฌธํ์ ์๋์ง ํ์ธ
- ๋ฐฑํธ๋ํน ์๊ณ ๋ฆฌ์ฆ์ ์ํํ ํจ์ backtracking(cur_node, cur_sheep, cur_wolf)๋ฅผ ์ ์ํ๋ค.
- cur_node๋ฅผ ๋ฐํ์ผ๋ก max_sheep๋ฅผ ๊ฐฑ์ ํ๋ค.
- ํ์ฌ ๋ ธ๋์ ์ฐ๊ฒฐ๋ ๋ ธ๋๋ฅผ ํ๋์ฉ ๋ฐฉ๋ฌธํ๋ค.
- ๋ง์ฝ ์ฐ๊ฒฐ๋ ๋ ธ๋์ visited๋ฅผ ํ์ธํด์ ํ์ฌ (cur_node, cur_sheep)์ด ์๋ ๊ฒฝ์ฐ์๋ง ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๋ค.
- ๋ฐฉ๋ฌธํ ๋
ธ๋์ ์ ํน์ ๋๋๊ฐ ์๊ณ , ์ฌ์ ํ ์์ด ๋๋๋ณด๋ค ๋ง๋ค๋ฉด
- info[๋ฐฉ๋ฌธํ ๋ ธ๋]๋ฅผ -1๋ก ๋ฐ๊ฟ์ฃผ๊ณ , cur_sheep๊ณผ cur_wolf๋ฅผ ๊ฐฑ์ ํ๋ค.
- ์ด ๋, visited_way[๋ฐฉ๋ฌธํ ๋ ธ๋][๊ฐฑ์ ๋ cur_sheep][cur_wolf] ์ ๋ณด๋ฅผ ์ ์ฅํ๋ค.
- backtracking(๋ฐฉ๋ฌธํ ๋ ธ๋, ๊ฐฑ์ ๋ cur_sheep, ๊ฐฑ์ ๋ cur_wolf)๋ฅผ ์ฌ๊ทํธ์ถ ํ๋ค, info์ visited๋ฅผ ๋ณต๊ตฌํด์ค๋ค.
- backtracking(0, 1, 0)๋ฅผ ํธ์ถํด ๊ฐฑ์ ๋ max_sheep๋ฅผ ๋ฐํํ๋ค.
๐ ์ ๋ต ์ฝ๋
max_sheep = 0
def solution(info, edges):
global max_sheep
node_count = len(info)
glassland = [[] for _ in range(node_count)]
for a, b in edges:
glassland[a].append(b)
glassland[b].append(a)
visited = [[[False]*18 for _ in range(18)] for _ in range(node_count)]
def backtracking(cur_node, cur_sheep, cur_wolf):
global max_sheep
max_sheep = max(max_sheep, cur_sheep)
for next_node in glassland[cur_node]:
if not visited[next_node][cur_sheep][cur_wolf]:
next_sheep, next_wolf = cur_sheep, cur_wolf
next_node_info = info[next_node]
if next_node_info == 1:
next_wolf += 1
elif next_node_info == 0:
next_sheep += 1
if next_sheep > next_wolf:
info[next_node] = -1
visited[next_node][next_sheep][next_wolf] = 1
backtracking(next_node, next_sheep, next_wolf)
info[next_node] = next_node_info
visited[next_node][next_sheep][next_wolf] = 0
info[0] = -1
visited[0][1][0] = 1
backtracking(0, 1, 0)
return max_sheep
728x90