- 論壇徽章:
- 0
|
現(xiàn)在我們用堆棧解決一個有意思的問題,定義一個二維數(shù)組:
int maze[5][5] = {
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,
};
它表示一個迷宮,其中的1表示墻壁,0表示可以走的路,只能橫著走或豎著走,不能斜著走,要求編程序找出從左上角到右下角的路線。
3、上一節(jié)我們實現(xiàn)了一個基于堆棧的程序,然后改寫成遞歸程序,用函數(shù)調(diào)用的棧幀替代自己實現(xiàn)的堆棧。本節(jié)的DFS算法也是基于堆棧的,請把它改寫成遞歸程序,這樣改寫可以避免使用predecessor數(shù)據(jù)結構,想想該怎么做。
倒序打。- #include <stdio.h>
- #define MAX_ROW 5
- #define MAX_COL 5
- struct point { int row, col; };
- 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},
- };
- int explore(struct point p){
- if (p.row == MAX_ROW - 1 /* goal */
- && p.col == MAX_COL - 1)
- return 1;
- struct point next;
- if (p.col+1 < MAX_COL /* right */
- && maze[p.row][p.col+1] == 0){
- maze[p.row][p.col+1] = 2;
- next.row=p.row;
- next.col=p.col+1;
- if(explore(next)==1){
- printf("(%d, %d), ", next.row, next.col);
- return 1;
- }
- }
- if (p.row+1 < MAX_ROW /* down */
- && maze[p.row+1][p.col] == 0)
- {
- maze[p.row+1][p.col] = 2;
- next.row=p.row+1;
- next.col=p.col;
- if(explore(next)==1){
- printf("(%d, %d), ", next.row, next.col);
- return 1;
- }
- }
- if (p.col-1 >= 0 /* left */
- && maze[p.row][p.col-1] == 0)
- {
- maze[p.row][p.col-1] = 2;
- next.row=p.row;
- next.col=p.col-1;
- if(explore(next)==1){
- printf("(%d, %d), ", next.row, next.col);
- return 1;
- }
- }
- if (p.row-1 >= 0 /* up */
- && maze[p.row-1][p.col] == 0)
- {
- maze[p.row-1][p.col] = 2;
- next.row=p.row-1;
- next.col=p.col;
- if(explore(next)==1){
- printf("(%d, %d), ", next.row, next.col);
- return 1;
- }
- }
- return -1;
- }
- int main(void)
- {
- struct point p = { 0, 0 };
- if(explore(p)!=1){
- printf("no path!\n");
- }
- else
- printf("(%d, %d)\n", p.row, p.col);
- return 0;
- }
復制代碼 |
|