本程序使用循环队列初步实现广度遍历,还需要优化,比如改进针对'*'输出的判断语句。 代码如下: #include "stdafx.h" #include <stdio.h> #define MAX_ROW 5 #define MAX_COL 5 #define QUEUE_SIZE 20 #define HIGH_INDEX (QUEUE_SIZE-1) struct point { int row, col, predecessor; } queue[QUEUE_SIZE]; int head = 0, tail = 0; //queue head and rear unsigned long enqueue_count = 0, dequeue_count = 0; //operation counts bool enqueue(struct point p) //Insert element { //queue[tail%QUEUE_SIZE] = p; //tail = (tail+1) % QUEUE_SIZE; if (enqueue_count-dequeue_count<QUEUE_SIZE) { queue[tail] = p; enqueue_count++; if (tail == HIGH_INDEX) { tail = 0; } else tail++; return true; } else return false; } struct point dequeue(void) //delete element { int prehead; //int prehead = head; //head = (head+1) % QUEUE_SIZE;; //return queue[prehead%QUEUE_SIZE]; if (enqueue_count != dequeue_count) { prehead = head; dequeue_count++; if (head == HIGH_INDEX) { head = 0; } else head++; } return queue[prehead]; } bool is_empty(void) { if((head == tail) && (enqueue_count == dequeue_count)) return true; else return false; } int maze[MAX_ROW][MAX_COL] = { 0,1,0,0,0, 0,1,0,1,0, 0,0,0,0,0, 0,1,1,1,0, 0,0,0,1,0, }; void print_maze(void) { int i,j; for (i = 0; i<MAX_ROW; i++) { for (j=0;j<MAX_COL;j++) { if(maze[i][j] == '*') printf("%c",maze[i][j]); else printf("%d",maze[i][j]); } putchar('/n'); } printf("*********/n"); } void visit(int row, int col) { struct point visit_point = {row,col,head-1}; maze[row][col] = '*'; enqueue(visit_point); } int _tmain(int argc, _TCHAR* argv[]) { struct point p = {0,0,-1}; maze[p.row][p.col] = '*'; enqueue(p); while(!is_empty()){ p = dequeue(); if (p.row == MAX_ROW-1 && p.col == MAX_COL-1) break; if (p.col+1 < MAX_COL && maze[p.row][p.col+1] == 0) visit(p.row,p.col+1); if (p.row+1 < MAX_ROW && maze[p.row+1][p.col] == 0) visit(p.row+1,p.col); if (p.col-1 >= 0 && maze[p.row][p.col-1] == 0) visit(p.row,p.col-1); if (p.row-1 >= 0 && maze[p.row-1][p.col] == 0) visit(p.row-1,p.col); print_maze(); } if (p.row == MAX_ROW-1 && p.col == MAX_COL-1) { printf("(%d, %d)/n",p.row, p.col); while(p.predecessor != -1){ p = queue[p.predecessor]; printf("(%d, %d)/n",p.row, p.col); } } else { printf("No path!/n"); } return 0; }