華爲面試題:迷宮問題 C語言源碼

定義一個二維數組N*M(其中2<=N<=10;2<=M<=10),如5 × 5數組下所示:


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表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。入口點爲[0,0],既第一空格是可以走的路。

Input

一個N × M的二維數組,表示一個迷宮。數據保證有唯一解,不考慮有多解的情況,即迷宮只有一條通道。

Output

左上角到右下角的最短路徑,格式如樣例所示。

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
輸出
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MAX_PATH 256

int maze[10][10] = {0};
int route[100][2] = {0};
int main()
{
	int row=0,line=0;
	scanf("%d %d",&row,&line);
	for (int i=0;i<row;i++)
	{
		for (int j=0;j<line;j++)
		{
			scanf("%d",&maze[i][j]);
		}
	}
	//走迷宮
	//堆棧:記錄上一個位置
	int xcurrent = 0;
	int ycurrent = 0;
	int count=0;
	while(true)
	{
		if (maze[xcurrent+1][ycurrent]==0 && xcurrent+1<row)
		{
			//返回上一個位置
			if (route[count-1][0]==xcurrent+1 && route[count-1][1]==ycurrent)
			{
				maze[xcurrent][ycurrent]=1;//設置爲牆
				count--;
				xcurrent++;
			}
			else
			{
				route[count][0]=xcurrent;
				route[count][1]=ycurrent;
				count++;
				xcurrent++;
			}
		}
		else if (maze[xcurrent][ycurrent+1]==0 && ycurrent<line)
		{
			if (route[count-1][0]==xcurrent && route[count-1][1]==ycurrent+1)
			{
				maze[xcurrent][ycurrent]=1;//設置爲牆
				count--;
				ycurrent++;
			}
			else
			{
				route[count][0]=xcurrent;
				route[count][1]=ycurrent;
				count++;
				ycurrent++;
			}
		}
		else if (maze[xcurrent-1][ycurrent]==0 && xcurrent-1>=0)
		{
			if (route[count-1][0]==xcurrent-1 && route[count-1][1]==ycurrent)
			{
				maze[xcurrent][ycurrent]=1;//設置爲牆
				count--;
				xcurrent--;
			}
			else
			{
				route[count][0]=xcurrent;
				route[count][1]=ycurrent;
				count++;
				xcurrent--;
			}
		}
		else if (maze[xcurrent][ycurrent-1]==0 && ycurrent-1>=0)
		{
			if (route[count-1][0]==xcurrent && route[count-1][1]==ycurrent-1)
			{
				maze[xcurrent][ycurrent]=1;//設置爲牆
				count--;
				ycurrent--;
			}
			else
			{
				route[count][0]=xcurrent;
				route[count][1]=ycurrent;
				count++;
				ycurrent--;
			}
		}
		if (xcurrent==row-1 && ycurrent==line-1)
		{
			route[count][0]=xcurrent;
			route[count][1]=ycurrent;
			count++;
			break;
		}
	}
	
	for (int i=0;i<count;i++)
	{
		printf("(%d,%d)\n",route[i][0],route[i][1]);
	}

	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章