深度优先算法DFS
英雄要从H点出发,去解救位于M点的美女。
迷宫的围墙用#表示,带*号的位置表示有杀手埋伏,这些点都是不能走的,
那么英雄要最少走多少步才能解救美女呢?
package myalgorithm; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class ShortPath { /*全局最短路径*/ public int stepnum = 999; /*构建11*11的迷宫,英雄H在(1,1)的位置出发,去解救美女M(6,8)*/ char[][] graph = { {'#','#','#','#','#','#','#','#','#','#','#'}, {'#','H','_','_','*','_','_','*','_','_','#'}, {'#','_','_','_','_','_','_','_','_','_','#'}, {'#','_','*','_','_','_','*','_','_','_','#'}, {'#','_','_','_','*','_','_','_','_','*','#'}, {'#','_','_','_','_','_','_','*','_','*','#'}, {'#','_','*','_','_','_','_','_','M','_','#'}, {'#','*','_','_','*','_','_','_','_','_','#'}, {'#','_','_','_','_','_','_','_','_','_','#'}, {'#','_','_','_','*','_','_','_','_','_','#'}, {'#','#','#','#','#','#','#','#','#','#','#'}, }; /*初始标记数组都为0*/ public int[][] mark = new int[graph.length][graph.length]; /*每一个位置有四种选择:右下左上*/ public int[][] choose = { {0,1}, {1,0}, {0,-1}, {-1,0} }; /*采用递归的DFS算法*/ public void DFS(int x,int y, int step) { /*找到美女M*/ if (graph[x][y] == 'M') { if(step < stepnum) { stepnum = step; } return;//找到之后立即返回,不再继续 } //新位置 int tx = 0; int ty = 0; for(int i=0;i<4;i++) { tx = x + choose[i][0]; ty = y + choose[i][1]; if(graph[tx][ty] != '#' && graph[tx][ty] != '*' && mark[tx][ty] == 0) { mark[tx][ty] = 1;//标记该点已经走过 DFS(tx,ty,step+1); mark[tx][ty] = 0;//取消该点的标记 } } return; } public static void main(String[] args) { ShortPath my = new ShortPath();long start1 = System.currentTimeMillis(); my.mark[1][1] = 1; my.DFS(1,1,0);long end1 = System.currentTimeMillis(); System.out.println("DFS step: " + my.stepnum + " time:" + (end1-start1)); } }
非常耗时:DFS step: 12 time:109830