BFS和DFS解决迷宫最短路径问题 C++

BFS和DFS解决迷宫最短路径问题 C++

BFS

#include 
#include 
using namespace std;

int a[100][100], v[100][100];
struct point
{
	int x;
	int y;
	int step;
};

queue<point> r;
int dx[4] = {0,1,0,-1};//四个方向右下左上
int dy[4] = {1,0,-1,0};
int main()
{
	int n, m,startx,starty,p,q;
	scanf_s("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			scanf_s("%d", &a[i][j]);
	scanf_s("%d%d%d%d", &startx,&starty,&p,&q);

	//BFS
	point start;
	start.x = startx;
	start.y = starty;
	start.step = 0;
	r.push(start);//
	v[startx][starty] = 1;
	int flag = 1;
	while (!r.empty())
	{
		int x = r.front().x, y = r.front().y;
		if (x == p && y == q)
		{
			flag = 1;
			printf("%d", r.front().step);
			break;
		}
		for (int k = 0; k <= 3; k++)
		{
			int tx, ty;
			tx = x + dx[k];
			ty = y + dy[k];
			if (a[tx][ty] == 1 && v[tx][ty] == 0)
			{
				//入队
				point temp;
				temp.x = tx;
				temp.y = ty;
				temp.step = r.front().step + 1;
				r.push(temp);
				v[tx][ty] = 1;
			}
		}
		r.pop();//拓展完需要将队首出队

	}

	if (flag == 0)
	{
		printf("no answer!");
	}
	return 0;
}

DFS

#include 
using namespace std;
int p, q,m,n;
int  minnum = 9999;
int a[100][100];//`1表示空地,2表示障碍物
int v[100][100];//0表示未访问,1表示访问 
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
void dfs(int x, int y,int step)
{
	if (x == p && y == q)
	{
		if (step < minnum)
		{
			minnum = step;
		}
		return;
	}

	//顺时针试探
	//右
	if (a[x][y + 1] == v[x][y + 1] == 0)
	{
		a[x][y + 1] = 1;
		dfs(x, y + 1, step + 1);
		//回溯后
		v[x][y + 1] = 0;
	}

	//顺时针
	for (int k = 0; k <= 3; k++)
	{
		int tx, ty;
		tx = x + dx[k];
		ty = x + dy[k];
		if (a[tx][ty] == 1 && v[tx][ty] == 0)
		{
			v[tx][ty] = 1;
			dfs(tx,ty,step+1);
			v[tx][ty] = 0;
		}
		

	}
	/*
	//下
	if (a[x+1][y] == v[x+1][y] == 0)
	{
		a[x + 1][y] = 1;
		dfs(x+1, y, step + 1);
		//回溯后
		v[x + 1][y] = 0;
	}
	//左
	if (a[x][y - 1] == v[x][y - 1] == 0)
	{
		a[x][y - 1] = 1;
		dfs(x, y - 1, step + 1);
		//回溯后
		v[x][y - 1] = 0;
	}
	//上
	if (a[x - 1][y] == v[x - 1][y] == 0)
	{
		a[x - 1][y] = 1;
		dfs(x - 1, y, step + 1);
		//回溯后
		v[x - 1][y] = 0;
	}
	*/
	return;
}
int main()
{
	int startx, starty;
	scanf_s("%d%d",&m,&n);
	for (int i = 1; i <= m; i++)
		for (int j = 1; j <= n; j++)
			scanf_s("%d", &a[i][j]);

	scanf_s("%d%d%d%d", &startx, &starty, &p, &q);
	v[startx][starty] = 1;
	dfs(startx, startx, 0);
	printf("%d", minnum);
	return 0;
}

你可能感兴趣的:(刷题,深度优先,c++)