package algorithm;
public class Algorithm2 {
/**
*
* s 0 1 0
* 0 0 0 0
* 0 0 1 0
* 0 1 e 0
* 0 0 0 1
*
*
* 豎軸爲x軸
* 橫軸爲Y軸
*/
/**
* 迷宮找最短路徑 0代表平地,1代表障礙物,s代表起點,e代表終點 (起點和終點肯定也是0)
*/
static int[][] next = {
{0, 1},//右
{1, 0},//下
{0, -1},//左
{-1, 0}//上
};
static int[][] allLocation = new int[50][50];
static int[][] marks = new int[50][50];
static {
//我這列從1,1開始賦值
allLocation[1][1] = 0;
allLocation[1][2] = 0;
allLocation[1][3] = 1;
allLocation[1][4] = 0;
allLocation[2][1] = 0;
allLocation[2][2] = 0;
allLocation[2][3] = 0;
allLocation[2][4] = 0;
allLocation[3][1] = 0;
allLocation[3][2] = 0;
allLocation[3][3] = 1;
allLocation[3][4] = 0;
allLocation[4][1] = 0;
allLocation[4][2] = 1;
allLocation[4][3] = 0;
allLocation[4][4] = 0;
allLocation[5][1] = 0;
allLocation[5][2] = 0;
allLocation[5][3] = 0;
allLocation[5][4] = 1;
}
static int endX, endY;//終點
static int startX, startY;//起點
static int min = 99999;
static int n = 5;//行數
static int m = 4;//列數
public static void main(String[] args) {
startX = 1;
startY = 1;
endX = 4;
endY = 3;
marks[startX][startY] = 1;
dfs(startX,startY,0);
System.out.println("最短步數爲:"+min);
}
//深度優先遍歷
public static void dfs(int x, int y, int step) {
int tx, ty, k;
//判斷是否到達終點的位置
if (x == endX && y == endY) {
//更新最小值
if (step < min) {
min = step;
}
return;
}
//枚舉四種走法 這裏的走法是 右 下 左 上
for (k = 0; k <= 3; k++) {
//計算下一個點的座標
tx = x + next[k][0];
ty = y + next[k][1];
//判斷是否越界
if (tx < 1 || tx > n || ty < 1 || ty > m) {
continue;
}
//判斷該點是否爲障礙物或者已經在路徑中
if (allLocation[tx][ty] == 0 && marks[tx][ty] == 0) {
marks[tx][ty] = 1;//已經走過了
dfs(tx, ty, step + 1);
marks[tx][ty] = 0;//取消標記位
}
}
return;
}
}
尋找迷宮中的最少步數的一個深度優先遍歷的小算法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.