ro-project / index.html
daxdan's picture
undefined - Initial Deployment
d4daf75 verified
Raw History Blame Contribute Delete
32.8 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dijkstra's Algorithm Solver</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
.graph-container {
width: 100%;
height: 400px;
border: 2px solid #e2e8f0;
border-radius: 0.5rem;
position: relative;
overflow: hidden;
background-color: #f8fafc;
}
.node {
position: absolute;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #3b82f6;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
cursor: move;
user-select: none;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
transition: all 0.2s ease;
}
.node:hover {
transform: scale(1.1);
background-color: #2563eb;
}
.node-start {
background-color: #10b981;
}
.node-end {
background-color: #ef4444;
}
.node-visited {
background-color: #8b5cf6;
animation: pulse 1.5s infinite;
}
.node-shortest-path {
background-color: #f59e0b;
}
.edge {
position: absolute;
height: 2px;
background-color: #64748b;
transform-origin: 0 0;
z-index: 1;
}
.edge-weight {
position: absolute;
background-color: white;
padding: 0 4px;
font-size: 12px;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="container mx-auto px-4 py-8">
<header class="mb-8">
<h1 class="text-3xl font-bold text-center text-indigo-700 mb-2">
<i class="fas fa-route mr-2"></i> Dijkstra's Algorithm Solver
</h1>
<p class="text-center text-gray-600 max-w-2xl mx-auto">
Visualize and solve shortest path problems using Dijkstra's algorithm. Enter nodes, edges, and weights to find the optimal path.
</p>
</header>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Left Panel - Input Form -->
<div class="lg:col-span-1 bg-white rounded-lg shadow-md p-6">
<h2 class="text-xl font-semibold mb-4 text-gray-800">Graph Configuration</h2>
<div class="mb-6">
<h3 class="font-medium mb-2 text-gray-700">Nodes</h3>
<div class="flex mb-2">
<input type="text" id="nodeName" placeholder="Node name" class="flex-grow px-3 py-2 border rounded-l focus:outline-none focus:ring-2 focus:ring-indigo-500">
<button id="addNodeBtn" class="bg-indigo-600 text-white px-4 py-2 rounded-r hover:bg-indigo-700 transition">
<i class="fas fa-plus"></i> Add
</button>
</div>
<div class="max-h-40 overflow-y-auto border rounded p-2" id="nodeList">
<p class="text-sm text-gray-500 italic">No nodes added yet</p>
</div>
</div>
<div class="mb-6">
<h3 class="font-medium mb-2 text-gray-700">Edges</h3>
<div class="grid grid-cols-3 gap-2 mb-2">
<select id="nodeFrom" class="col-span-1 px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
<option value="">From</option>
</select>
<select id="nodeTo" class="col-span-1 px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
<option value="">To</option>
</select>
<input type="number" id="edgeWeight" placeholder="Weight" class="col-span-1 px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
</div>
<button id="addEdgeBtn" class="w-full bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition mb-2">
<i class="fas fa-link"></i> Add Edge
</button>
<div class="max-h-40 overflow-y-auto border rounded p-2" id="edgeList">
<p class="text-sm text-gray-500 italic">No edges added yet</p>
</div>
</div>
<div class="mb-6">
<h3 class="font-medium mb-2 text-gray-700">Algorithm</h3>
<div class="grid grid-cols-2 gap-2 mb-2">
<select id="startNode" class="px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
<option value="">Start Node</option>
</select>
<select id="endNode" class="px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
<option value="">End Node</option>
</select>
</div>
<button id="runAlgorithmBtn" class="w-full bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 transition mb-2">
<i class="fas fa-play"></i> Run Algorithm
</button>
<button id="resetBtn" class="w-full bg-gray-200 text-gray-800 px-4 py-2 rounded hover:bg-gray-300 transition">
<i class="fas fa-redo"></i> Reset
</button>
</div>
</div>
<!-- Middle Panel - Graph Visualization -->
<div class="lg:col-span-2">
<div class="bg-white rounded-lg shadow-md p-6 mb-6">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-semibold text-gray-800">Graph Visualization</h2>
<div class="space-x-2">
<button id="toggleModeBtn" class="bg-indigo-100 text-indigo-700 px-3 py-1 rounded-md text-sm hover:bg-indigo-200 transition">
<i class="fas fa-vector-square mr-1"></i> Edit Mode
</button>
<div class="tooltip inline-block">
<button id="helpBtn" class="bg-gray-100 text-gray-700 px-3 py-1 rounded-md text-sm hover:bg-gray-200 transition">
<i class="fas fa-question-circle"></i>
</button>
<span class="tooltiptext">Drag nodes to reposition</span>
</div>
</div>
</div>
<div class="graph-container" id="graphContainer"></div>
</div>
<!-- Results Section -->
<div class="bg-white rounded-lg shadow-md p-6">
<h2 class="text-xl font-semibold mb-4 text-gray-800">Algorithm Results</h2>
<div id="resultsContainer">
<div class="p-4 bg-gray-50 rounded-md text-gray-600">
<p class="italic">Run the algorithm to see results...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const nodeNameInput = document.getElementById('nodeName');
const addNodeBtn = document.getElementById('addNodeBtn');
const nodeListDiv = document.getElementById('nodeList');
const nodeFromSelect = document.getElementById('nodeFrom');
const nodeToSelect = document.getElementById('nodeTo');
const edgeWeightInput = document.getElementById('edgeWeight');
const addEdgeBtn = document.getElementById('addEdgeBtn');
const edgeListDiv = document.getElementById('edgeList');
const startNodeSelect = document.getElementById('startNode');
const endNodeSelect = document.getElementById('endNode');
const runAlgorithmBtn = document.getElementById('runAlgorithmBtn');
const resetBtn = document.getElementById('resetBtn');
const graphContainer = document.getElementById('graphContainer');
const resultsContainer = document.getElementById('resultsContainer');
const toggleModeBtn = document.getElementById('toggleModeBtn');
// Graph state
let nodes = [];
let edges = [];
let isEditMode = true;
let selectedNode = null;
let offsetX, offsetY;
// Initialize the app
init();
function init() {
addEventListeners();
updateUI();
}
function addEventListeners() {
addNodeBtn.addEventListener('click', addNode);
nodeNameInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') addNode();
});
addEdgeBtn.addEventListener('click', addEdge);
runAlgorithmBtn.addEventListener('click', runAlgorithm);
resetBtn.addEventListener('click', resetGraph);
toggleModeBtn.addEventListener('click', toggleEditMode);
// For node dragging
graphContainer.addEventListener('mousedown', startDragging);
graphContainer.addEventListener('mousemove', dragNode);
graphContainer.addEventListener('mouseup', stopDragging);
graphContainer.addEventListener('mouseleave', stopDragging);
}
function addNode() {
const nodeName = nodeNameInput.value.trim();
if (!nodeName) {
showAlert('Please enter a node name', 'error');
return;
}
if (nodes.some(node => node.name === nodeName)) {
showAlert('Node already exists', 'error');
return;
}
const newNode = {
name: nodeName,
x: Math.random() * (graphContainer.offsetWidth - 40),
y: Math.random() * (graphContainer.offsetHeight - 40)
};
nodes.push(newNode);
nodeNameInput.value = '';
updateNodeDropdowns();
renderGraph();
showAlert(`Node "${nodeName}" added successfully`, 'success');
}
function addEdge() {
const fromNode = nodeFromSelect.value;
const toNode = nodeToSelect.value;
const weight = parseInt(edgeWeightInput.value);
if (!fromNode || !toNode) {
showAlert('Please select both nodes', 'error');
return;
}
if (isNaN(weight) || weight <= 0) {
showAlert('Please enter a valid positive weight', 'error');
return;
}
if (fromNode === toNode) {
showAlert('Cannot create edge to the same node', 'error');
return;
}
const edgeExists = edges.some(edge =>
(edge.from === fromNode && edge.to === toNode) ||
(edge.from === toNode && edge.to === fromNode)
);
if (edgeExists) {
showAlert('Edge already exists between these nodes', 'error');
return;
}
edges.push({
from: fromNode,
to: toNode,
weight: weight
});
edgeWeightInput.value = '';
renderGraph();
updateEdgeList();
showAlert(`Edge added: ${fromNode} ↔ ${toNode} (${weight})`, 'success');
}
function runAlgorithm() {
const startNode = startNodeSelect.value;
const endNode = endNodeSelect.value;
if (!startNode || !endNode) {
showAlert('Please select both start and end nodes', 'error');
return;
}
if (nodes.length === 0 || edges.length === 0) {
showAlert('Please add nodes and edges first', 'error');
return;
}
// Run Dijkstra's algorithm
const result = dijkstra(nodes, edges, startNode, endNode);
// Visualize the process
visualizeAlgorithm(result);
// Display results
displayResults(result);
}
function dijkstra(nodes, edges, startNode, endNode) {
// Initialize distances and previous nodes
const distances = {};
const previous = {};
const visited = new Set();
const unvisited = new Set(nodes.map(node => node.name));
nodes.forEach(node => {
distances[node.name] = Infinity;
previous[node.name] = null;
});
distances[startNode] = 0;
// Main algorithm loop
while (unvisited.size > 0) {
// Find the unvisited node with the smallest distance
let currentNode = getMinDistanceNode(unvisited, distances);
// If we've reached the end node, we can stop early
if (currentNode === endNode) break;
// Mark as visited
unvisited.delete(currentNode);
visited.add(currentNode);
// Find all neighbors of current node
const neighbors = edges.filter(edge =>
edge.from === currentNode || edge.to === currentNode
);
// Update distances for each neighbor
neighbors.forEach(edge => {
const neighbor = edge.from === currentNode ? edge.to : edge.from;
if (visited.has(neighbor)) return;
const newDistance = distances[currentNode] + edge.weight;
if (newDistance < distances[neighbor]) {
distances[neighbor] = newDistance;
previous[neighbor] = currentNode;
}
});
}
// Reconstruct the shortest path
const shortestPath = [];
let current = endNode;
while (current !== null) {
shortestPath.unshift(current);
current = previous[current];
}
return {
distances: distances,
previous: previous,
shortestPath: shortestPath,
visitedNodes: Array.from(visited)
};
}
function getMinDistanceNode(unvisited, distances) {
let minDistance = Infinity;
let minNode = null;
unvisited.forEach(node => {
if (distances[node] < minDistance) {
minDistance = distances[node];
minNode = node;
}
});
return minNode;
}
function visualizeAlgorithm(result) {
// Reset all node classes
document.querySelectorAll('.node').forEach(node => {
node.classList.remove('node-visited', 'node-shortest-path');
});
// Animate visited nodes
let delay = 0;
result.visitedNodes.forEach((nodeName, index) => {
setTimeout(() => {
const nodeElement = document.querySelector(`.node[data-name="${nodeName}"]`);
if (nodeElement) {
nodeElement.classList.add('node-visited');
}
}, delay);
delay += 500;
});
// Animate shortest path
setTimeout(() => {
let pathDelay = 0;
result.shortestPath.forEach(nodeName => {
setTimeout(() => {
const nodeElement = document.querySelector(`.node[data-name="${nodeName}"]`);
if (nodeElement) {
nodeElement.classList.add('node-shortest-path');
}
}, pathDelay);
pathDelay += 500;
});
}, delay);
}
function displayResults(result) {
const { distances, shortestPath } = result;
let html = `
<div class="space-y-4">
<div class="p-4 bg-blue-50 rounded-md">
<h3 class="font-semibold text-blue-800 mb-2">Shortest Path Details</h3>
<p class="text-gray-700">
<span class="font-medium">Total distance:</span> ${distances[shortestPath[shortestPath.length - 1]]}
</p>
<p class="text-gray-700">
<span class="font-medium">Path:</span> ${shortestPath.join(' → ')}
</p>
</div>
<div class="p-4 bg-green-50 rounded-md">
<h3 class="font-semibold text-green-800 mb-2">Distances from Start Node</h3>
<div class="grid grid-cols-3 gap-2">
`;
// Add distance for each node
nodes.forEach(node => {
html += `
<div class="text-sm bg-white p-2 rounded border">
<span class="font-medium">${node.name}:</span> ${distances[node.name] !== Infinity ? distances[node.name] : '∞'}
</div>
`;
});
html += `
</div>
</div>
<div class="p-4 bg-purple-50 rounded-md">
<h3 class="font-semibold text-purple-800 mb-2">Algorithm Steps</h3>
<p class="mb-2 text-gray-700">
1. Initialize all nodes with infinite distance except start node (0)<br>
2. Select unvisited node with smallest distance as current node<br>
3. For current node, examine its unvisited neighbors and calculate tentative distances<br>
4. Update neighbor distances if a shorter path is found<br>
5. Mark current node as visited<br>
6. Repeat until all nodes are visited or the end node is reached
</p>
</div>
</div>
`;
resultsContainer.innerHTML = html;
}
function resetGraph() {
nodes = [];
edges = [];
nodeNameInput.value = '';
edgeWeightInput.value = '';
updateNodeDropdowns();
updateEdgeList();
renderGraph();
resultsContainer.innerHTML = `
<div class="p-4 bg-gray-50 rounded-md text-gray-600">
<p class="italic">Run the algorithm to see results...</p>
</div>
`;
showAlert('Graph has been reset', 'success');
}
function toggleEditMode() {
isEditMode = !isEditMode;
toggleModeBtn.innerHTML = isEditMode ?
'<i class="fas fa-vector-square mr-1"></i> Edit Mode' :
'<i class="fas fa-eye mr-1"></i> View Mode';
showAlert(isEditMode ? 'Edit mode activated' : 'View mode activated', 'info');
}
function updateNodeDropdowns() {
// Update node dropdowns in edge creation form
nodeFromSelect.innerHTML = '<option value="">From</option>';
nodeToSelect.innerHTML = '<option value="">To</option>';
startNodeSelect.innerHTML = '<option value="">Start Node</option>';
endNodeSelect.innerHTML = '<option value="">End Node</option>';
nodes.forEach(node => {
const option = `<option value="${node.name}">${node.name}</option>`;
nodeFromSelect.innerHTML += option;
nodeToSelect.innerHTML += option;
startNodeSelect.innerHTML += option;
endNodeSelect.innerHTML += option;
});
// Update node list display
if (nodes.length === 0) {
nodeListDiv.innerHTML = '<p class="text-sm text-gray-500 italic">No nodes added yet</p>';
} else {
nodeListDiv.innerHTML = nodes.map(node => `
<div class="flex justify-between items-center mb-1 last:mb-0 p-2 bg-gray-50 rounded">
<span class="font-medium">${node.name}</span>
<button class="text-red-500 hover:text-red-700 text-sm" onclick="removeNode('${node.name}')">
<i class="fas fa-times"></i>
</button>
</div>
`).join('');
}
}
function updateEdgeList() {
if (edges.length === 0) {
edgeListDiv.innerHTML = '<p class="text-sm text-gray-500 italic">No edges added yet</p>';
} else {
edgeListDiv.innerHTML = edges.map((edge, index) => `
<div class="flex justify-between items-center mb-1 last:mb-0 p-2 bg-gray-50 rounded">
<span>${edge.from} ↔ ${edge.to} (${edge.weight})</span>
<button class="text-red-500 hover:text-red-700 text-sm" onclick="removeEdge(${index})">
<i class="fas fa-times"></i>
</button>
</div>
`).join('');
}
}
function renderGraph() {
graphContainer.innerHTML = '';
// Render edges first (so they appear behind nodes)
edges.forEach(edge => {
const fromNode = nodes.find(node => node.name === edge.from);
const toNode = nodes.find(node => node.name === edge.to);
if (!fromNode || !toNode) return;
const x1 = fromNode.x + 20;
const y1 = fromNode.y + 20;
const x2 = toNode.x + 20;
const y2 = toNode.y + 20;
const edgeElement = document.createElement('div');
edgeElement.className = 'edge';
edgeElement.style.width = `${Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2))}px`;
edgeElement.style.left = `${x1}px`;
edgeElement.style.top = `${y1}px`;
edgeElement.style.transform = `rotate(${Math.atan2(y2 - y1, x2 - x1)}rad)`;
graphContainer.appendChild(edgeElement);
// Add weight label
const weightElement = document.createElement('div');
weightElement.className = 'edge-weight';
weightElement.textContent = edge.weight;
weightElement.style.left = `${(x1 + x2) / 2}px`;
weightElement.style.top = `${(y1 + y2) / 2 - 10}px`;
graphContainer.appendChild(weightElement);
});
// Render nodes
nodes.forEach(node => {
const nodeElement = document.createElement('div');
nodeElement.className = 'node';
nodeElement.textContent = node.name;
nodeElement.style.left = `${node.x}px`;
nodeElement.style.top = `${node.y}px`;
nodeElement.setAttribute('data-name', node.name);
// Highlight start and end nodes
if (startNodeSelect.value === node.name) {
nodeElement.classList.add('node-start');
}
if (endNodeSelect.value === node.name) {
nodeElement.classList.add('node-end');
}
graphContainer.appendChild(nodeElement);
});
}
// Node dragging functionality
function startDragging(e) {
if (!isEditMode) return;
const nodeElement = e.target.closest('.node');
if (!nodeElement) return;
selectedNode = nodes.find(node => node.name === nodeElement.getAttribute('data-name'));
if (!selectedNode) return;
offsetX = e.clientX - selectedNode.x;
offsetY = e.clientY - selectedNode.y;
e.preventDefault();
}
function dragNode(e) {
if (!selectedNode || !isEditMode) return;
selectedNode.x = e.clientX - offsetX;
selectedNode.y = e.clientY - offsetY;
// Ensure node stays within container bounds
selectedNode.x = Math.max(0, Math.min(graphContainer.offsetWidth - 40, selectedNode.x));
selectedNode.y = Math.max(0, Math.min(graphContainer.offsetHeight - 40, selectedNode.y));
renderGraph();
e.preventDefault();
}
function stopDragging() {
selectedNode = null;
}
function showAlert(message, type) {
const alerts = {
success: { color: 'bg-green-100 text-green-800', icon: 'check-circle' },
error: { color: 'bg-red-100 text-red-800', icon: 'exclamation-circle' },
info: { color: 'bg-blue-100 text-blue-800', icon: 'info-circle' }
};
const alertDiv = document.createElement('div');
alertDiv.className = `fixed top-4 right-4 z-50 ${alerts[type].color} px-4 py-3 rounded shadow-lg transition-opacity duration-300 opacity-0`;
alertDiv.style.minWidth = '300px';
alertDiv.innerHTML = `
<div class="flex items-center">
<i class="fas fa-${alerts[type].icon} mr-2"></i>
<p>${message}</p>
<button class="ml-auto" onclick="this.parentElement.parentElement.remove()">
<i class="fas fa-times"></i>
</button>
</div>
`;
document.body.appendChild(alertDiv);
// Trigger animation
setTimeout(() => {
alertDiv.style.opacity = '1';
// Auto-dismiss after 3 seconds
setTimeout(() => {
alertDiv.style.opacity = '0';
setTimeout(() => alertDiv.remove(), 300);
}, 3000);
}, 10);
// Make alert globally available
window.showAlert = showAlert;
}
// Make these functions globally available
window.removeNode = function(name) {
nodes = nodes.filter(node => node.name !== name);
// Remove any edges connected to this node
edges = edges.filter(edge => edge.from !== name && edge.to !== name);
updateNodeDropdowns();
updateEdgeList();
renderGraph();
showAlert(`Node "${name}" removed`, 'success');
};
window.removeEdge = function(index) {
const edge = edges[index];
edges.splice(index, 1);
updateEdgeList();
renderGraph();
showAlert(`Edge removed: ${edge.from} ↔ ${edge.to}`, 'success');
};
function updateUI() {
updateNodeDropdowns();
updateEdgeList();
renderGraph();
}
});
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=daxdan/ro-project" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>