class Grapg< T > {
verteces: T [ ] = [ ] ;
adjList: Map< T , T [ ] > = new Map ( ) ;
addVertex ( v: T ) {
this . verteces. push ( v) ;
this . adjList. set ( v, [ ] ) ;
}
addEdge ( v: T , w: T ) {
this . adjList. get ( v) ?. push ( w) ;
this . adjList. get ( w) ?. push ( v) ;
}
printEdges ( ) {
this . verteces. forEach ( ( vertex) => {
console . log ( ` ${ vertex} -> ${ this . adjList. get ( vertex) ?. join ( ' ' ) } ` ) ;
} ) ;
}
BFS ( ) {
if ( this . verteces. length === 0 ) return ;
const visited = new Set< T > ( ) ;
visited. add ( this . verteces[ 0 ] ) ;
const queue = [ this . verteces[ 0 ] ] ;
while ( queue. length) {
const v = queue. shift ( ) ! ;
console . log ( v) ;
const vEdges = this . adjList. get ( v) ;
if ( ! vEdges) continue ;
for ( const e of vEdges) {
if ( ! visited. has ( e) ) {
visited. add ( e) ;
queue. push ( e) ;
}
}
}
}
DFS ( ) {
if ( this . verteces. length === 0 ) return ;
const visited = new Set< T > ( ) ;
visited. add ( this . verteces[ 0 ] ) ;
const stack = [ this . verteces[ 0 ] ] ;
while ( stack. length) {
const v = stack. pop ( ) ! ;
console . log ( v) ;
const vEdges = this . adjList. get ( v) ;
if ( ! vEdges) return ;
for ( let i = vEdges. length - 1 ; i >= 0 ; i-- ) {
const e = vEdges[ i] ;
if ( ! visited. has ( e) ) {
stack. push ( e) ;
visited. add ( e) ;
}
}
}
}
}
const graph = new Grapg< string > ( ) ;
for ( let i = 0 ; i < 9 ; i++ ) {
graph. addVertex ( String. fromCharCode ( 65 + 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' ) ;
graph. printEdges ( ) ;
console . log ( 'BFS' ) ;
graph. BFS ( ) ;
console . log ( 'DFS' ) ;
graph. DFS ( ) ;