最短経路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();
	})