๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ•˜๋…ธ์ด์˜ ํƒ‘ ์ดํ•ดํ•˜๊ธฐ

by ์„œ์•„๋ž‘๐Ÿ˜ 2022. 2. 18.

 

 
 
 
๊ฒ‰์œผ๋กœ ๋ณด๊ธฐ์—๋Š” ํ•˜๋…ธ์ด์˜ ํƒ‘์—์„œ ์žฌ๊ท€์˜ ์กฐ๊ฑด์ธ ๋ถ€๋ถ„ ๋ถ„ํ• ์˜ ๊ฒฝ์šฐ๊ฐ€ ์—†์–ด๋ณด์ด์ง€๋งŒ, ์ž์„ธํžˆ ๋“ค์—ฌ๋‹ค ๋ณด๋ฉด ๋ฐ˜๋“œ์‹œ ์กด์žฌํ•œ๋‹ค.
ํ•˜๋…ธ์ด์˜ ํƒ‘์€ ๊ธฐ๋‘ฅ 3๊ฐœ๋Š” ๊ณ ์ •์ด๊ธฐ ๋•Œ๋ฌธ์— ์‹œ์ž‘์ (From), ์˜ฎ๊ธธ ์ง€์ (To), ๋‚˜๋จธ์ง€ ์ง€์ (Mid)๋กœ ๊ตฌ์„ฑ๋œ๋‹ค.
 

 

 
์›๋ฐ˜ 3๊ฐœ ์˜ˆ๋ฅผ ๋“ค์–ด๋ณด์ž.(์›๋ฐ˜์„ 1์—์„œ 3์œผ๋กœ ์˜ฎ๊ธฐ๋Š” ๊ณผ์ •, N: 3, From: 1, Mid: 2, To: 3)

 

 
 
 
์ฒซ๋ฒˆ์งธ ๋นจ๊ฐ„ ์˜์—ญ์€ ์›๋ฐ˜ 2๊ฐœ๋ฅผ (1)์—์„œ (2)๋กœ ์˜ฎ๊ธฐ๋Š” ๊ณผ์ •์ด๋‹ค.(N: 2, From: 1, Mid: 3, To: 2)
์ด ํ›„, 1->3์€ ๊ฐ€์žฅ ํฐ ์›๋ฐ˜์„ ๋ชฉ์ (To)์ง€์ ์œผ๋กœ ์˜ฎ๊ธฐ๋Š” ๊ณผ์ •์ด๋‹ค.
๋‘๋ฒˆ์งธ ๋นจ๊ฐ„ ์˜์—ญ์€ ์›๋ฐ˜ 2๊ฐœ๋ฅผ (2)์—์„œ (3)๋กœ ์˜ฎ๊ธฐ๋Š” ๊ณผ์ •์ด๋‹ค.(N: 2, From: 2, Mid: 1, To: 3)
 
 
์ •๋ฆฌํ•˜๋ฉด,
hanoi(3)์˜ ๊ฒฐ๊ณผ๋Š”
hanoi(2)๋ฅผ ๋‚˜๋จธ์ง€ ์ง€์ ์œผ๋กœ ๋จผ์ € ์˜ฎ๊ธฐ๊ณ ,
๊ฐ€์žฅ ํฐ ์›๋ฐ˜์„ ๋ชฉ์ ์ง€์ ์œผ๋กœ ์˜ฎ๊ธฐ๊ณ ,
hanoi(2)๋ฅผ ๋ชฉ์ ์ง€์ ์œผ๋กœ ์˜ฎ๊ธฐ๋Š” ๊ณผ์ •์ด ๋œ๋‹ค.
 
์ด๋ฅผ ์ผ๋ฐ˜ํ™” ํ•˜๋ฉด
 
hanoi(n)(1,2,3) = hanoi(n-1)(1,3,2) + move(1,3) + hanoi(n-1)(2,1,3) ์ด ๋˜๋ฉฐ
 
 
๋” ์ผ๋ฐ˜ํ™” ์‹œ์ผœ๋ณด๊ฒ ๋‹ค.
 
hanoi(n)(From,Mid,To) = hanoi(n-1)(From,To,Mid) + move(From,To) + hanoi(n-1)(Mid,From,To)๊ฐ€ ๋œ๋‹ค.
 
 
์ฝ”๋“œ๋กœ ํ‘œํ˜„ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

 
    }
void hanoi(int n, int From, int Mid, int To) 
{
    if (n == 1)
        printf("1 : %d -> %d\n", From, To);
    else
    { 
        hanoi(n - 1, From, To, Mid);
        printf("%d : %d -> %d\n", n, From, To);
        hanoi(n - 1, Mid, From, To);
    }
}
}
 

 

 

๋Œ“๊ธ€