zoukankan      html  css  js  c++  java
  • 迷宫最近距离





    广搜代码如下:

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    
    public class Main
    {
    	public static final int[][] maze = new int[][] {
    		{0,1,0,0,0,1,1,1,0,1,0,1},
    		{0,0,0,1,0,0,0,0,1,0,0,1},
    		{0,1,0,1,0,1,1,1,0,1,0,0},
    		{0,1,0,0,0,0,0,1,0,0,1,1},
    		{0,0,0,0,1,0,0,0,0,0,0,0},
    		{0,0,1,0,0,0,1,0,0,0,1,0},
    		{0,0,1,0,0,0,0,0,1,0,0,0},
    		{1,0,0,1,0,1,0,0,0,1,0,1},
    		{0,0,1,0,1,0,1,0,1,0,0,0},
    		{0,0,0,0,0,1,0,0,0,1,1,0},
    		{0,0,0,0,0,1,0,0,0,0,0,0},
    		{0,1,0,1,0,0,0,1,0,1,0,0}
    	};
    	public static final int N = 12;
    	public static int sx, sy, gx, gy;
    	public static int[] dx = new int[] {1, 0, -1, 0};
    	public static int[] dy = new int[] {0, 1, 0, -1};
    	public static int[][] d = new int[150][150];//记录到该点最小步数
    	public static final int INF = 10000000;
    	public static class Point
    	{
    		public int x, y;
    		public Point(int x, int y)
    		{
    			this.x = x;
    			this.y = y;
    		}
    	}
    	public static void main(String[] args)
    	{
    		Scanner cin = new Scanner(System.in);
    		sx = cin.nextInt();
    		sy = cin.nextInt();
    		gx = cin.nextInt();
    		gy = cin.nextInt();
    		cin.close();
    		System.out.println(bfs());
    	}
    	public static int bfs()
    	{
    		Queue<Point> queue = new LinkedList<Point>();
    		for (int i = 0; i < N; ++i)
    		{
    			for (int j = 0; j < N; ++j)
    			{
    				d[i][j] = INF;//初始化
    			}
    		}
    		queue.add(new Point(sx, sy));
    		d[sx][sy] = 0;//到起点的步数为0
    		while (!queue.isEmpty())
    		{
    			Point p = queue.poll();
    			if (p.x == gx && p.y == gy)	break;
    			for (int i = 0; i < 4; ++i)
    			{
    				int nx = p.x + dx[i];
    				int ny = p.y + dy[i];
    				if (nx >= 0 && nx < N && ny >= 0 && ny < N && maze[nx][ny] != 1 && d[nx][ny] == INF)
    				{
    					queue.add(new Point(nx, ny));
    					d[nx][ny] = d[p.x][p.y] + 1;
    				}
    			}
    		}
    		//到达不了的情况
    		if (d[gx][gy] == INF)
    		{
    			return 10000;
    		}
    		return d[gx][gy];
    	}
    }
    
    ========================================Talk is cheap, show me the code=======================================
    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    OA系统权限管理设计方案【转】
    UML类图几种关系的总结
    在pl/sql中使用exp/imp工具实现oracle数据导出/导入
    page 的范围
    JSP页面跳转的五种方法
    Start with...Connect By
    秒杀系统架构
    对系统负载的理解
    sort(7)
    cat(6)
  • 原文地址:https://www.cnblogs.com/lcy0515/p/9179841.html
Copyright © 2011-2022 走看看