zoukankan      html  css  js  c++  java
  • 迷宫最短路径

    /*
    现在有这样的一个迷宫,S表示起始位置,E表示结束位置,在迷宫中有一些障碍‘#’,
    不能走障碍位置。那么问最少需要多少步可以从起始位置走到重点位置
    */
    
    #include <iostream>
    #include <stdio.h>
    #define N 100
    /*******************
    N用于确定地图矩阵的最大行或列
    *******************/
    using namespace std;
    struct queue
    {
    	char c;
    	int x, y, dis;
    };
    /*******************
    定义一个结构类型,x,y指示坐标位置,dis指示节点到起始点的距离
    c用于存储迷宫字符
    *******************/
    int main()
    {
    	struct queue que[N*N];
    	char maze[N][N] = { 0 };
    		int r, c, sx, sy;   //r指示迷宫矩阵的行数,c指示迷宫矩阵的列数,sx,sy用于存储起始点的坐标
    	cin >> r >> c;
    	for (int i = 0; i < r; i++)
    	{
    		for (int j = 0; j < c; j++)
    		{
    			cin >> maze[i][j]; //先从屏幕上读取迷宫矩阵
    			if (maze[i][j] == 'S')  //起始点
    			{
    				sy = i;
    				sx = j;
    			}
    		}
    	}
    	int vis[N][N] = { 0 };  //用于记录是否搜索过某一节点,为0表示没被搜索过,为1表示已搜索过
    	int dx[] = { 1, 0, 0, -1 };
    	int dy[] = { 0, 1, -1, 0 };
    	/******************
    	dx[],dy[]数组比较关键,通过这两个数组可以实现对中心点四周的节点的搜索
    	******************/
    	int front = -1, rear = -1;
    	que[++rear].c = maze[sy][sx];
    	que[rear].x = sx;
    	que[rear].y = sy;
    	que[rear].dis = 0;
    	vis[sx][sy] = 1;
    	/**********************
    	这一块实现上述的步骤1
    	**********************/
    	while (front < rear)
    	{
    		++front;
    		if (que[front].c == 'E')
    		{
    			cout << que[front].dis << endl;
    			system("pause");
    			return 0;
    		}
    		else
    		{
    			for (int i = 0; i < 4; i++)
    			{
    				int tx = que[front].x + dx[i];
    				int ty = que[front].y + dy[i];
    				if (tx >= 0 && tx < c && ty >= 0 && ty < r
    					&& !vis[ty][tx] && maze[ty][tx] != '#')
    					/**********************
    					此处保证了搜索节点一定位于迷宫矩阵内同时目标节点不是碍,
    					且目标节点未被搜索过
    					**********************/
    				{
    					que[++rear].c = maze[ty][tx];
    					que[rear].x = tx;
    					que[rear].y = ty;
    					que[rear].dis = que[front].dis + 1;
    					vis[ty][tx] = 1;
    				}
    			}
    		}
    	}
    	cout << -1<<endl;
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    用户态和内核态
    Spring Cloud构建微服务架构:服务网关(路由配置)【Dalston版】
    为什么说分布式事务不再适用于微服务架构
    基于selenium的二次开发
    Python常用方法
    深入浅出runloader
    python socket
    python API接口测试框架
    python装饰器
    python多进程安全
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/11459204.html
Copyright © 2011-2022 走看看