封装
const {queue} = require('../../队列/基于链表的队列/LinkQueue');
function Dictionary(){
this.group = {};
this.size = 0;
Dictionary.prototype.set = function (key,val){
if (!(key in this.group)) this.size +=1;
this.group[key] = val;
}
Dictionary.prototype.get = function (key){
if (key in this.group) return this.group[key];
return null;
}
Dictionary.prototype.toString = function (){
let str = '';
for (let key in this.group){
str += this.group[key]+' ';
}
return str;
}
}
function Graph(){
this.vertexes = [];
this.edges = new Dictionary();
Graph.prototype.addVertex = function (v){
this.vertexes.push(v);
this.edges.set(v,[]);
}
Graph.prototype.addEdge = function (v1,v2){
this.edges.get(v1).push(v2);
this.edges.get(v2).push(v1);
}
Graph.prototype.BFS = function (fistv,Handle){
let colors = this.initColor();
let que = new queue();
que.enQueue(fistv);
while (!que.isEmpty()){
let v = que.deQueue();
colors[v] = 'gray';
let vlist = this.edges.get(v);
for (let i = 0; i < vlist.length; i++) {
if (colors[vlist[i]] === 'white'){
colors[vlist[i]] = 'gray';
que.enQueue(vlist[i]);
}
}
Handle(v);
colors[v] = 'black';
}
}
Graph.prototype.DFS = function (firstv,handle){
this.DFSVisit(firstv,this.initColor(),handle);
}
Graph.prototype.DFSVisit = function (v,colors,handle){
colors[v] = 'gray';
handle(v);
let vertexs = this.edges.get(v);
for (let i = 0; i < vertexs.length; i++) {
let e = vertexs[i];
if (colors[e] === 'white'){
colors[e] = 'gray';
this.DFSVisit(e,colors,handle);
}
}
colors[v] = 'black';
}
Graph.prototype.initColor = function (){
let colors = [];
for (let i = 0; i < this.vertexes.length; i++) {
colors[this.vertexes[i]] = 'white'
}
return colors
}
Graph.prototype.toString = function (){
let str = '';
for (let i = 0; i < this.vertexes.length; i++) {
let str2 = '';
for (let j = 0; j < this.edges.get(this.vertexes[i]).length; j++) {
str2 += this.edges.get(this.vertexes[i])[j]+" "
}
str += this.vertexes[i]+"->"+str2+"\r\n";
}
return str;
}
}
let graph = new Graph();
let str = '';
let str1 = '';
function handle(v){
str += v+" ";
}
function handle1(v){
str1 += v+" ";
}
let myVertex = ['A','B','C','D','E','F','G','H','I'];
for (let i = 0; i < myVertex.length; i++) {
graph.addVertex(myVertex[i]);
}
graph.addEdge('A','B');
graph.addEdge('A','C');
graph.addEdge('A','D');
graph.addEdge('C','D');
graph.addEdge('C','G');
graph.addEdge('D','G');
graph.addEdge('D','H');
graph.addEdge('B','E');
graph.addEdge('B','F');
graph.addEdge('E','I');
console.log(graph.toString());
graph.BFS('A',handle);
graph.DFS('H',handle1);
console.log(str);
console.log(str1);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!