JavaScript圖結構

JavaScript圖結構

//圖結構
function Graph(){
	//保持所有頂點
	this.vertexes = []
	//保存所有邊
	this.edges = {}
	
	/*
	* 1. 添加頂點(參數爲要添加的頂點)
	*/ 
	Graph.prototype.addVertex = function(v){
		this.vertexes.push(v)
		//用數組保存與此頂點組成邊的另一些頂點
		this.edges[v] = []
	}
 /*
 * 2. 添加邊(參數爲組成邊的兩個頂點)
 */ 
	Graph.prototype.addEdge = function(v1, v2){
		this.edges[v1].push(v2)
		this.edges[v2].push(v1) 
	}
	/*
	* 3. toString方法
	*/ 
	Graph.prototype.toString = function(){
		let resultString = ''
		this.vertexes.forEach(eachVertex => {
			let eachStr = eachVertex + ' => '
			this.edges[eachVertex].forEach(eachEdge => {
				eachStr += eachEdge + ' '
			})
			resultString += eachStr + '\n'
		})
		return resultString
	}
	/*
	* 4. 初始化頂點狀態顏色
	* 
	*/
	Graph.prototype.initColor = function(){
		let colors = {}
		this.vertexes.forEach(item => {
			//初始化所有頂點狀態顏色爲白色(表示未探測,未訪問)
			colors[item] = 'white'
		})
		return colors
	}
	/*
	* 5. 廣度優先搜索
	*/ 
	Graph.prototype.bfs = function(firstV, callback){
		//初始化頂點狀態顏色
		let colors = this.initColor()
		//創建隊列
		let queue = []
		queue.push(firstV)
		//將頂點狀態顏色改爲灰色(表示已探測,未訪問)
		colors[firstV] = 'gray'
		while(queue.length != 0){
			//從隊列取出最前面的頂點
			let currentV = queue.shift()
			//獲取與此頂點組成邊的其他頂點
			let listV = this.edges[currentV]
			//遍歷與此頂點相連的其他頂點,將未探測過的頂點加入到隊列(防止重複探測)
			listV.forEach(item => {
				if (colors[item] == 'white'){
					colors[item] = 'gray'
					queue.push(item)
				}
			})
			//訪問此頂點
			callback(currentV)
			//將此頂點狀態顏色改爲黑色(表示已訪問)
			colors[currentV] = 'black'
		}
	}
	/*
	* 6.1 深度優先搜索
	*/ 
	Graph.prototype.dfs = function(firstV, callback){
		let colors = this.initColor()
		this.dfsTraversal(firstV, colors, callback)
	}
	/*
	* 6.2 深度優先搜索內置方法
	*/ 
	Graph.prototype.dfsTraversal = function(v, colors, callback){
		colors[v] = 'gray'
		callback(v)
		let listV = this.edges[v]
		
		listV.forEach(item => {
			if (colors[item] == 'white'){
				this.dfsTraversal(item, colors, callback)
			}
		})
		colors[v] = 'black'
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章