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

    给定一个大小为 N×M的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点。

    限制条件

    N, M ≤ 100

    输入

    10
    10
    #S######.#
    ......#..#
    .#.##.##.#
    .#........
    ##.##.####
    ....#....#
    .#######.#
    ....#.....
    .####.###.
    ....#...G#
    

    输出

    22
    宽度优先搜索按照距开始状态由近及远的顺序进行搜索,因此可以很容易地用来求最短路径、最少操作之类问题的答案

    java实现

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    class P{
    	int x;
    	int y;
    	public P(int x, int y) {
    		super();
    		this.x = x;
    		this.y = y;
    	}
    	public int getX() {
    		return x;
    	}
    	public void setX(int x) {
    		this.x = x;
    	}
    	public int getY() {
    		return y;
    	}
    	public void setY(int y) {
    		this.y = y;
    	}
    	
    }
    public class Main {
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner scn = new Scanner(System.in);
    		int N = scn.nextInt();
    		int M = scn.nextInt();
    		int sx=0,sy=0,ex=0,ey=0;
    		char arr[][];
    		arr=new char[N][M];
    		for(int i=0;i<N;i++) {
    			arr[i]=scn.next().toCharArray();
    		}
    		for(int i=0;i<N;i++) {
    			for(int j=0;j<M;j++) {
    				if(arr[i][j]=='S') {
    					sx=i;
    					sy=j;
    				}
    				if(arr[i][j]=='G') {
    					ex=i;
    					ey=j;
    				}
    			}
    		}
    		int arr2[][]=new int[N][M];
    		for(int i=0;i<N;i++) {
    			for(int j=0;j<M;j++) {
    				arr2[i][j]=10000;
    			}
    		}
    		int arr3[] = {-1,0,1,0};
    		int arr4[] = {0,-1,0,1};
    		Queue<P> que = new LinkedList();
    		que.add(new P(sx,sy));
    		arr2[sx][sy]=0;
    		while(que!=null) {
    			P p =que.poll();
    			if(p.getX()==ex&&p.getY()==ey)
    				break;
    			for (int i=0;i<4;i++) {
    				int x = p.x+arr3[i];
    				int y = p.y+arr4[i];
    				if(x>=0&&y>=0&&x<N&&y<M&&arr2[x][y]==10000&&arr[x][y]!='#') {
    					que.add(new P(x,y));
    					arr2[x][y]=arr2[p.x][p.y]+1;
    				}
    			}
    		}
    		System.out.println(arr2[ex][ey]);
    	}
    	
    }
    
  • 相关阅读:
    C++类中的封装-9
    递归神经网络
    卷积神经网络
    Tensorflow人工智能神经网络学习
    右键弹出菜单 并动态新增菜单子项
    sql 列转行
    sql 删除表中某字段的重复数据
    疑难问题解决
    jquery ashx交互 返回list 循环json输入信息
    jquery 控件赋值
  • 原文地址:https://www.cnblogs.com/zhangguangxiang/p/14232567.html
Copyright © 2011-2022 走看看