Hanoi塔
#include <stdio.h>
int count = 0;
void Move(int num, char X, char Y)
{
printf("move %d from %c to %c\n", num, X, Y);
count++;
}
void Hanoi(int n, char A, char B, char C)
{
if (n == 1)
Move(1, A, C);
else
{
Hanoi(n - 1, A, C, B);
Move(n, A, C);
Hanoi(n - 1, B, A, C);
}
}
int main()
{
Hanoi(4, 'A', 'B', 'C');
printf("%d steps in total\n", count);
return 0;
}
八皇后问题
#include <stdio.h>
#define CHESS_LEN 8
int count = 0;
int queens[CHESS_LEN] = {0};
int CheckPlace(int row_now, int col_now)
{
int col_last;
for (int row_last = 0; row_last < row_now; row_last++)
{
col_last = queens[row_last];
if (col_now == col_last)
return 0;
else if ((row_now - col_now) == (row_last - col_last))
return 0;
else if ((row_now + col_now) == (row_last + col_last))
return 0;
}
return 1;
}
void PrintChess()
{
for (int i = 0; i < CHESS_LEN; i++)
{
for (int j = 0; j < CHESS_LEN; j++)
{
if (queens[i] != j)
printf("O");
else
printf("@");
}
printf("\r\n");
}
printf("########################################################\n");
}
void FindPlace(int row)
{
for (int col = 0; col < CHESS_LEN; col++)
{
if (CheckPlace(row, col))
{
queens[row] = col;
if (row == (CHESS_LEN - 1))
{
count++;
PrintChess();
return;
}
FindPlace(row + 1);
}
}
}
int main()
{
FindPlace(0);
printf("%d results in total", count);
return 0;
}