图形:
邻接矩阵:
两点之间有边则设为1。
代码实现:
#include
#include
#define MAX_SIZE 8
typedef int Status;
Status graph[8][8] = {
// A B C D E F G H
{0, 1, 1, 1, 0, 0, 0, 0}, // A
{1, 0, 1, 0, 1, 0, 0, 0}, // B
{1, 1, 0, 1, 1, 0, 0, 1}, // C
{1, 0, 1, 0, 0, 1, 1, 0}, // D
{0, 1, 1, 0, 0, 0, 0, 1}, // E
{0, 0, 0, 1, 0, 0, 0, 1}, // F
{0, 0, 0, 1, 0, 0, 0, 1}, // G
{0, 0, 1, 0, 1, 1, 1, 0}, // H
};
typedef char ElemType;
typedef struct Queue
{
ElemType *head, *rear;
} Queue;
void initQueue(Queue *Q)
{
Q->head = (ElemType *)malloc(MAX_SIZE * sizeof(ElemType));
if ( !Q->head )
{
printf("init defeat!\n");
}
Q->rear = Q->head;
}
void printPoint(Queue *Q)
{
printf(">> ");
int row;
ElemType *tmp = Q->head;
while ( tmp != Q->rear )
{
row = *(tmp);
printf("%c ", row);
for (int i = 0; i < 8; i++)
{
if ( 1 == graph[row-65][i] )
{
*(Q->rear) = i+65;
Q->rear ++;
for (int j = 0; j < 8; j++)
{
graph[j][i] = 0; // 标记已走过的点
}
}
}
tmp ++;
}
}
void destoryQueue(Queue *Q)
{
free(Q->head);
}
int main(void)
{
char start;
Queue queue;
initQueue(&queue);
printf("Input start point:");
scanf("%c", &start);
*(queue.rear) = start;
queue.rear ++;
for (int i = 0; i < 8; i++)
{
graph[i][start-65] = 0;
}
printPoint(&queue);
destoryQueue(&queue);
return 0;
}
运行结果:
Input start point:A
>> A B C D E H F G
Input start point:B
>> B A C E D H F G
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)