const edges = [
{ from: 'A', to: 'B', weight: 4 },
{ from: 'A', to: 'C', weight: 2 },
{ from: 'B', to: 'C', weight: 1 },
{ from: 'B', to: 'D', weight: 5 },
{ from: 'C', to: 'D', weight: 8 },
{ from: 'C', to: 'E', weight: 10 },
{ from: 'D', to: 'E', weight: 2 },
{ from: 'E', to: 'A', weight: 3 },
]
function bellmanFord(edges, startNode) {
const distances = {}
edges.forEach((edge) => {
distances[edge.from] = Infinity
distances[edge.to] = Infinity
})
distances[startNode] = 0
for (let i = 0; i < Object.keys(distances).length - 1; i++) {
edges.forEach(({ from, to, weight }) => {
if (distances[from] + weight < distances[to]) {
distances[to] = distances[from] + weight
}
})
}
edges.forEach(({ from, to, weight }) => {
if (distances[from] + weight < distances[to]) {
throw new Error('음수 가중치 사이클이 존재합니다.')
}
})
return distances
}
const startNode = 'A'
try {
const shortestDistances = bellmanFord(edges, startNode)
console.log(`최단 거리 테이블 (${startNode}에서 시작):`, shortestDistances)
} catch (error) {
console.error(error.message)
}
const graph = [
[0, 3, Infinity, 5],
[2, 0, Infinity, 4],
[Infinity, 1, 0, Infinity],
[Infinity, Infinity, 2, 0],
]
function floydWarshall(graph) {
const nodes = graph.length
const dist = Array.from({ length: nodes }, () => Array(nodes).fill(Infinity))
for (let i = 0; i < nodes; i++) {
for (let j = 0; j < nodes; j++) {
dist[i][j] = graph[i][j]
}
}
for (let k = 0; k < nodes; k++) {
for (let i = 0; i < nodes; i++) {
for (let j = 0; j < nodes; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
return dist
}
const shortestDistances = floydWarshall(graph)
console.log('모든 쌍 최단 거리 테이블:')
console.table(shortestDistances)
const graph = {
A: { B: 1, C: 4 },
B: { A: 1, C: 2, D: 5 },
C: { A: 4, B: 2, D: 1 },
D: { B: 5, C: 1 },
}
function dijkstra(graph, startNode) {
const distances = {}
for (let node in graph) {
distances[node] = Infinity
}
distances[startNode] = 0
const visited = new Set()
const queue = []
queue.push({ node: startNode, distance: 0 })
while (queue.length > 0) {
queue.sort((a, b) => a.distance - b.distance)
const { node: currentNode, distance: currentDistance } = queue.shift()
if (visited.has(currentNode)) continue
visited.add(currentNode)
for (let neighbor in graph[currentNode]) {
const totalDistance = currentDistance + graph[currentNode][neighbor]
if (totalDistance < distances[neighbor]) {
distances[neighbor] = totalDistance
queue.push({ node: neighbor, distance: totalDistance })
}
}
}
return distances
}
const startNode = 'A'
const shortestDistances = dijkstra(graph, startNode)
console.log(`최단 거리 테이블 (${startNode}에서 시작):`, shortestDistances)
const graph = {
A: ['B', 'C'],
B: ['D', 'E'],
C: ['F', 'G'],
D: [],
E: [],
F: [],
G: [],
}
function bfs(graph, start) {
const visited = new Set()
const queue = [start]
const result = []
while (queue.length > 0) {
const node = queue.shift()
if (!visited.has(node)) {
visited.add(node)
result.push(node)
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
queue.push(neighbor)
}
}
}
}
return result
}
function dfsRecursive(graph, node, visited = new Set(), result = []) {
if (!visited.has(node)) {
visited.add(node)
result.push(node)
for (const neighbor of graph[node]) {
dfsRecursive(graph, neighbor, visited, result)
}
}
return result
}
function dfsIterative(graph, start) {
const visited = new Set()
const stack = [start]
const result = []
while (stack.length > 0) {
const node = stack.pop()
if (!visited.has(node)) {
visited.add(node)
result.push(node)
for (const neighbor of graph[node].slice().reverse()) {
if (!visited.has(neighbor)) {
stack.push(neighbor)
}
}
}
}
return result
}
console.log('BFS 탐색 순서:', bfs(graph, 'A'))
console.log('DFS 탐색 순서 (재귀):', dfsRecursive(graph, 'A'))
console.log('DFS 탐색 순서 (반복):', dfsIterative(graph, 'A'))
그래프