最近学习数据结构,碰到了这个经典迷宫最短路径问题,整理一下思路
- 把起点放入队中
- 队处理数据,如果和终点一致那么就返回成功,如果不一致需要遍历一下起点周围的点
- 依次把周围点加入队列,最后dequeue,原点
- 重复处理队列数据
// 队列
function Queue() {
let items = [];
this.enqueue = (val) => {
items.push(val);
};
this.dequeue = () => {
return items.shift();
};
this.head = () => {
return items[0];
};
this.isEmpty = () => {
return items.length === 0;
};
}
function Point() {
this.x;
this.y;
this.step;
}
let a = [
[1, 1, 2, 1],
[1, 1, 1, 1],
[1, 1, 2, 1],
[1, 2, 1, 1],
[1, 1, 1, 2],
];
let v = [];
let q = new Queue();
let dx = [0, 1, 0, -1];
let dy = [1, 0, -1, 0];
// 建立迷宫数组
function map(n, m, arr) {
for (let i = 0; i < n; i++) {
arr[i] = new Array();
for (let j = 0; j < m; j++) {
arr[i][j] = 0;
}
}
}
map(5, 4, v);
// 广度优先处理队列BFS
function BFS(startx, starty, r, c) {
let start = new Point();
start.x = startx;
start.y = starty;
start.step = 0;
q.enqueue(start);
v[startx][starty] = 1;
let flag = 0;
while (!q.isEmpty()) {
let x = q.head().x;
let y = q.head().y;
if (x === r && y === c) {
flag = 1;
console.log("到达了", q.head().step);
break;
}
for (let k = 0; k <= 3; k++) {
let tx, ty;
tx = x + dx[k];
ty = y + dy[k];
if (a[tx] && a[ty] && a[tx][ty] === 1 && v[tx][ty] === 0) {
let tmp = new Point();
tmp.x = tx;
tmp.y = ty;
tmp.step = q.head().step + 1;
q.enqueue(tmp);
v[tx][ty] == 1;
}
}
q.dequeue();
}
if (flag === 0) {
console.log("no answer");
}
}
BFS(0, 0, 3, 2);