Skip to content

Commit adb3ef3

Browse files
Merge branch 'main' into feat/bellman
2 parents a82a9b7 + 4511154 commit adb3ef3

File tree

7 files changed

+1004
-142
lines changed

7 files changed

+1004
-142
lines changed

src/App.jsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
import React from "react";
22
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
3-
import Homepage from "./pages/Homepage";
3+
import UnionFindPage from "../src/pages/graph/UnionFind.jsx"; // ✅ Import Union-Find Page
44
import SortingPage from "./pages/sorting/SortingPage";
55
import GraphPage from "./pages/graph/GraphPage";
6+
import Homepage from "./pages/Homepage.jsx";
67

78
function App() {
89
return (
910
<Router>
1011
<Routes>
1112
<Route path="/" element={<Homepage />} />
13+
<Route path="/graph/union-find" element={<UnionFindPage />} /> {/* ✅ Added route */}
1214
<Route path="/sorting" element={<SortingPage />} />
1315
<Route path="/graph" element={<GraphPage />} />
1416
</Routes>

src/algorithms/graph/unionFind.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// src/algorithms/graph/unionFind.js
2+
3+
class UnionFind {
4+
constructor(n) {
5+
this.parent = Array.from({ length: n }, (_, i) => i);
6+
this.rank = Array(n).fill(0);
7+
this.steps = []; // For visualization steps
8+
}
9+
10+
find(x) {
11+
this.steps.push({ type: "find-start", node: x });
12+
if (this.parent[x] !== x) {
13+
const root = this.find(this.parent[x]);
14+
this.steps.push({
15+
type: "path-compression",
16+
node: x,
17+
newParent: root,
18+
});
19+
this.parent[x] = root;
20+
}
21+
this.steps.push({ type: "find-end", node: x, root: this.parent[x] });
22+
return this.parent[x];
23+
}
24+
25+
union(x, y) {
26+
const rootX = this.find(x);
27+
const rootY = this.find(y);
28+
29+
this.steps.push({
30+
type: "union-start",
31+
x,
32+
y,
33+
rootX,
34+
rootY,
35+
});
36+
37+
if (rootX === rootY) {
38+
this.steps.push({ type: "same-set", x, y });
39+
return;
40+
}
41+
42+
if (this.rank[rootX] < this.rank[rootY]) {
43+
this.parent[rootX] = rootY;
44+
this.steps.push({
45+
type: "union",
46+
parent: rootY,
47+
child: rootX,
48+
});
49+
} else if (this.rank[rootX] > this.rank[rootY]) {
50+
this.parent[rootY] = rootX;
51+
this.steps.push({
52+
type: "union",
53+
parent: rootX,
54+
child: rootY,
55+
});
56+
} else {
57+
this.parent[rootY] = rootX;
58+
this.rank[rootX]++;
59+
this.steps.push({
60+
type: "union-rank",
61+
parent: rootX,
62+
child: rootY,
63+
});
64+
}
65+
}
66+
67+
getSteps() {
68+
return this.steps;
69+
}
70+
}
71+
72+
export default UnionFind;

0 commit comments

Comments
 (0)