알고리즘 하노이의 탑 자바 코드 정리

Posted by HULIA(휴리아)
2018. 10. 9. 20:51 뒷이야기들/취업이직준비채용공고

public class Main {

int count = 0;//전체 횟수


public static void main(String[] args) {

// TODO Auto-generated method stub

Main main = new Main();

main.solution(3);

}

public int[][] solution(int n) {

int[][] answer = new int [(int)Math.pow(2, n)-1][2];

answer = moveHanoi(1,2,3,n,answer);

for(int i=0; i<answer.length; i++){

System.out.print(answer[i][0]+"->");

System.out.println(answer[i][1]);

}

System.out.println(Arrays.deepToString(answer));

return answer;


}

public int[][] moveHanoi(int initial, int middle, int ffinal, int n, int[][]answer){

if(n==1){

answer[count][0]=initial;

answer[count][1]=ffinal;

++count;

}

else{

moveHanoi(initial, ffinal, middle, n-1, answer);

answer[count][0]=initial;

answer[count][1]=ffinal;

++count;

moveHanoi(middle, initial, ffinal, n-1, answer);

}

return answer;

}

}



참고

https://blog.martinwork.co.kr/theory/2018/10/07/hanoi-algorithm.html