๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค[Java] - (Level3)ํ•˜๋…ธ์ด์˜ ํƒ‘

by ์ฃผ๋ฐœ2 2020. 3. 17.
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/12946

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

์ฝ”๋“œ

class Solution {
  public static int[][] answer;
  public static int x = 0;
    
  // n๊ฐœ๋ฅผ other๊ธฐ๋‘ฅ์„ ์‚ฌ์šฉํ•ด from -> to๋กœ ์˜ฎ๊ธฐ๊ธฐ
  public static void hanoi(int n, int from, int other, int to){
      if(n == 0)
          return;
      hanoi(n-1, from, to, other);  // n-1๊ฐœ์˜ ์›ํŒ์„ ๋ชฉ์ ์ง€๊ฐ€ ์•„๋‹Œ ๊ณณ(other)๋กœ ์˜ฎ๊ฒจ๋†“์Œ.
      answer[x][0] = from;          // ๋งˆ์ง€๋ง‰ ์›ํŒ์„ ๋ชฉ์ ์ง€๋กœ ์˜ฎ๊น€.
      answer[x++][1] = to;          // ๋งˆ์ง€๋ง‰ ์›ํŒ์„ ๋ชฉ์ ์ง€๋กœ ์˜ฎ๊น€.
      hanoi(n-1, other, from, to);  // ๋ชฉ์ ์ง€๊ฐ€ ์•„๋‹Œ ๊ณณ(other)์— ์˜ฎ๊ฒจ๋†“์•˜๋˜ ์›ํŒ๋“ค์„ ๋ชฉ์ ์ง€๋กœ ์˜ฎ๊น€
  }
    
  public int[][] solution(int n) {
      int num = (int)Math.pow(2, n) - 1;    // ํ•˜๋…ธ์ด์˜ ์ด๋™ ํšŸ์ˆ˜: 2^n - 1
      answer = new int[num][2]; // ํšŸ์ˆ˜๋Š” num๋งŒํผ, ์—ด์€ 3๊ฐœ(์„ธ ๊ฐœ์˜ ๊ธฐ๋‘ฅ)
      hanoi(n, 1, 2, 3);
      return answer;
  }
}

ํ’€์ด

ํ•˜๋…ธ์ด์˜ํƒ‘ ์ด๋™ ํšŸ์ˆ˜๋Š” 2^n - 1 ์ด๋ผ๊ณ  ์™ธ์šฐ๊ณ  ์žˆ์—ˆ๋‹ค.

๊ธฐํƒ€ ์ž์„ธํ•œ ํ’€์ด๋Š” ์•„๋ž˜ ์ฐธ๊ณ 

๋ฐฑ์ค€ 11729๋ฒˆ ํ•˜๋…ธ์ดํƒ‘์ด๋™์ˆœ์„œ

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€