最短路径JS版

function GMaze(maze){
	// 数组对象,存放迷宫数组
	this.MazeSource = maze;
	// 实例变量
	this.Passage=0; //可以走的路
	this.Wall=1;  //墙,不可以通过
	this.Entry=2; // 入口
	this.Exit=3; // 出口
	this.Visited=4; // 走过的路
	this.EntryCell = null; // 入口对象
	this.ExitCell = null; // 出口对象
	this.mazeQueue = new Array();
	this.listCell = new Array();
}

GMaze.prototype.Init = function Init(){
	for(var i=0;i<this.MazeSource.length;i++)
		for(var j=0;j<this.MazeSource[i].length;j++){
			if(this.MazeSource[i][j] == 2)
				this.EntryCell = new Cell(i,j,'E');
			if(this.MazeSource[i][j] == 3)
				this.ExitCell = new Cell(i,j,'X');
		}

	if(this.EntryCell != null && this.ExitCell != null)
		return true;
	else
		return false;
}

GMaze.prototype.FindPath = function (){
	if(!this.Init()){
		alert('Maze initialized failed!');
		return;
	}

	var currentCell = this.EntryCell;

	while(!currentCell.Equals(this.ExitCell)){
		var i = currentCell.I;
		var j = currentCell.J;
		if (!currentCell.Equals(this.EntryCell)){  
			this.MazeSource[i][j] = this.Visited;
		}
		this.PushUnivisited(i - 1, j, 'U', currentCell);
		this.PushUnivisited(i + 1, j, 'D', currentCell);
		this.PushUnivisited(i, j - 1, 'L', currentCell);
		this.PushUnivisited(i, j + 1, 'R', currentCell);

		if (this.mazeQueue.length == 0){
			return false;
		}
		else{
			currentCell = this.mazeQueue.shift();
			this.listCell.push(currentCell);
		}
	}
	this.DisplayResult();
}

GMaze.prototype.PushUnivisited = function (i,j,des,parentCell){
	if (this.MazeSource[i][j] == this.Passage || this.MazeSource[i][j] == this.Exit)  {
		var tmp = new Cell(i, j, des);
		tmp.Parent = parentCell;
		this.mazeQueue.push(tmp);
	}
}

GMaze.prototype.DisplayResult = function (){
	if(this.listCell.length < 0){
		alert("Empty Result");
		return;
	}
	//这个是显示最短路径的倒序,从出口找入口,如果需要正序,把结果入栈。
	var cell = this.listCell[this.listCell.length-1];
	while(cell!=null){
		cell.Display();
		cell = cell.Parent;
	}
}

/* Cell class*/
function Cell(i,j,des){
	this.I = i;
	this.J = j;
	this.Destination=des;
	this.Parent=null;
}

Cell.prototype.Equals= function(cell){
	if(this.I == cell.I && this.J== cell.J)
		return true;
	else
		return false;
}

Cell.prototype.Display= function(){
	alert("I=" +String(this.I) + ' J=' + String(this.J) + " Destination=" + this.Destination);
}

 

调用方法:

$(document).ready(function(){
		//DisplayMaze();
    	var mz = new Array([1,1,1,1,1],[1,2,0,1,1],[1,0,0,3,1],[1,1,1,1,1]);
		var g = new GMaze(mz);
		g.FindPath();

		alert('new')
		mz = new Array([1,1,1,1,1,1],[1,2,0,0,0,1],[1,0,0,0,0,1],[1,0,0,0,3,1],[1,1,1,1,1,1]);
		 g = new GMaze(mz);
		g.FindPath();
	})



 

你可能感兴趣的:(function,String,null,Class)