zoukankan      html  css  js  c++  java
  • 迷宫 (maze)

    迷宫 (maze)

    题目背景

    相似题目:洛谷P1605 (题面相似)

    题目描述

    给定一个 (N imes M) 方格的迷宫,迷宫里有 (T) 处障碍,障碍处不可通过。给定起点坐标和终点坐标,问每个方格最多经过(1)次。在迷宫中移动有上下左右四种方式。保证起点上没有障碍。问从起点到终点的最短路径长度以及输出一条长度最短的路径经过的点的坐标。

    如果不存在起点到终点的路径则就输出(-1)

    输入格式

    第一行 (N) , (M)(T) , (N) 为行,(M) 为列,(T) 为障碍总数。

    第二行起点坐标 (SX) , (SY),终点坐标 (FX) , (FY)

    接下来 (T) 行,每行为障碍的坐标。

    输出格式

    如果存在解答则:

    第一行,输出最短路径的长度 (K)(起点终点也算在步数内),

    以下 (K) 行,每行包含两个整数 (I) , (J) ,意为经过第 (I) 行第 (J) 列的点,

    否则输出(-1)

    输入输出样例

    输入 #1
    2 2 1
    1 1 2 2
    1 2
    
    输出 #1
    3
    1 1
    2 1
    2 2
    

    数据范围

    (1 leq N imes M leq 1000)

    参考代码

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int n,m,t,sx,sy,fx,fy,ans=1000000,dx[4]= {0,1,0,-1},dy[4]= {1,0,-1,0};
    bool vis[1005][1005];
    struct node {
    	int x,y;
    } a[1000005],b[1000005];
    void dfs(int x,int y,int step) {
    	if(x==fx&&y==fy) {
    		if(step<ans) {
    			ans=step;
    			for(int i=2; i<=step; i++) {
    				b[i].x=a[i].x,b[i].y=a[i].y;
    			}
    			if(t==0&&ans<(abs(fx-sx)+abs(fy-sy)+2)) {
    				printf("%d
    ",ans);
    				for(int i=1; i<=ans; i++) {
    					printf("%d %d
    ",b[i].x,b[i].y);
    				}
    				exit(0);
    			}
    		}
    		return;
    	}
    	for(int i=0; i<4; i++) {
    		int nx=x+dx[i],ny=y+dy[i];
    		if(nx&&nx<=n&&ny&&ny<=m&&!vis[nx][ny]) {
    			vis[nx][ny]=true;
    			a[step+1].x=nx;
    			a[step+1].y=ny;
    			dfs(nx,ny,step+1);
    			vis[nx][ny]=false;
    			a[step+1].x=0;
    			a[step+1].y=0;
    		}
    	}
    }
    int main() {
    //	freopen("maze.in","r",stdin);
    //	freopen("maze.out","w",stdout);
    	cin>>n>>m>>t>>sx>>sy>>fx>>fy;
    	for(int i=1,x,y; i<=t; i++) {
    		cin>>x>>y;
    		vis[x][y]=true;
    	}
    	if(t==n*m-2) {
    		cout<<"-1"<<endl;
    		return 0;
    	}
    	vis[sx][sy]=true;
    	b[1].x=a[1].x=sx;
    	b[1].y=a[1].y=sy;
    	dfs(sx,sy,1);
    	if(ans==1000000) {
    		printf("-1
    ");
    	} else {
    		cout<<ans<<endl;
    		for(int i=1; i<=ans; i++) {
    			cout<<b[i].x<<" "<<b[i].y<<endl;
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    堆的应用
    1155 Heap Paths (30 分)(堆+dfs遍历)
    1099 Build A Binary Search Tree (30 分)(查找二叉树)
    1064 Complete Binary Search Tree (30 分)(二叉查找树)
    1043 Is It a Binary Search Tree (25 分)(二叉查找树)
    1053 Path of Equal Weight (30 分)(树的遍历)
    1106 Lowest Price in Supply Chain (25 分)(树的遍历)
    洛谷P1031均分纸牌(贪心平均数)
    洛谷P1045麦森数(高精度乘法)
    洛谷P1255数楼梯(大数,高精度加法)
  • 原文地址:https://www.cnblogs.com/jiupinzhimaguan/p/13499288.html
Copyright © 2011-2022 走看看