[Data structures]Hanoi

2019-9-16 写技术

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 1024

char stack[MAX][255];
int top = -1;

void printStack()
{
	int i;

	for(i=top; i>=0; i--){
		printf("%s\n", stack[i]);
	}
	printf("\n");
}

void hanoi(int n, char x, char y, char z)
{
	printStack();

	if(n==1){
		printf("%c -> %c\n", x, z);
	}else{
		sprintf(stack[++top], "%d, %d, %c, %c, %c", 6, n-1, x, z, y);
		hanoi(n-1, x, z, y);
		printStack();

		printf("%c -> %c\n", x, z);
		sprintf(stack[++top], "%d, %d, %c, %c, %c", 8, n-1, y, x, z);
		hanoi(n-1, y, x, z);
		printStack();
	}

	top--;
}

void main()
{
	printf("log.anycle.com\n\n");

	printf("Hanoi:\n");
	sprintf(stack[++top], "%d, %d, %c, %c, %c", 0, 3, 'a', 'b', 'c');
	hanoi(3, 'a', 'b', 'c');
	printf("\n");
}

标签: Data Structures data_structures

发表评论:

Powered by anycle 湘ICP备15001973号