题 意:给定一迷宫,输出从起点到终点的最短路径 思 路:BFS 学习点:BFS 源代码: #include <stdio.h> #define MAXN 6 #define nSize 5 int vis[MAXN][MAXN]; int nMap[MAXN][MAXN]; int faNode[MAXN][MAXN]; int nQueue[MAXN*MAXN]; int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; int nPath[MAXN * MAXN][3]; void funcInput(); void bfs(int nRow, int nCol); void funcOutput(int nRow, int nCol); int main() { funcInput(); bfs(0, 0); funcOutput(4, 4); return 0; } void funcInput() { int i, j; for (i = 0; i != nSize; ++i) { for (j = 0; j != nSize; ++j) { scanf("%d", &nMap[i][j]); vis[i][j] = 0; } } } void bfs(int nRow, int nCol) { int nR, nC; int cur, dir; int front = 0, rear = 0; int nFlag, visNode; cur = nRow * nSize + nCol; vis[nRow][nCol] = 1; faNode[nRow][nRow] = cur; nQueue[rear++] = cur; while (front != rear) { cur = nQueue[front++]; nRow = cur / nSize; nCol = cur % nSize; for (dir = 0; dir != 4; ++dir) { nR = nRow + dx[dir]; nC = nCol + dy[dir]; nFlag = (nR >= 0 && nR < nSize && nC >= 0 && nC < nSize && !vis[nR][nC] && !nMap[nR][nC]); if (nFlag) { visNode = nR * nSize + nC; nQueue[rear++] = visNode; vis[nR][nC] = 1; faNode[nR][nC] = cur; } } } } void funcOutput(int nRow, int nCol) { int nCnt; int fR, fC; nPath[0][0] = nRow; nPath[0][1] = nCol; nCnt = 1; while(1) { fR = faNode[nRow][nCol] / nSize; fC = faNode[nRow][nCol] % nSize; if (fR == nRow && fC == nCol) break; nPath[nCnt][0] = fR; nPath[nCnt][1] = fC; nCnt ++; nRow = fR; nCol = fC; } while(nCnt--) { printf("(%d, %d)/n", nPath[nCnt][0], nPath[nCnt][1]); } }