1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| class Solution { public: class UnionFind { public: vector<int> parent; vector<int> size; int n; int setCount; public: UnionFind(int _n): n(_n), setCount(_n), parent(_n), size(_n, 1) { iota(parent.begin(), parent.end(), 0); } int findset(int x) { return parent[x] == x ? x : parent[x] = findset(parent[x]); } bool unite(int x, int y) { x = findset(x); y = findset(y); if (x == y) { return false; } if (size[x] < size[y]) { swap(x, y); } parent[y] = x; size[x] += size[y]; --setCount; return true; } bool connected(int x, int y) { x = findset(x); y = findset(y); return x == y; } }; struct Node { int x, y, w; }; int minimumEffortPath(vector<vector<int>>& h) { int n = h.size(), m = h[0].size(); vector<Node> g; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i > 0) g.push_back(Node{i * m + j, i * m + j - m, abs(h[i][j] - h[i - 1][j])}); if (j > 0) g.push_back(Node{i * m + j, i * m + j - 1, abs(h[i][j] - h[i][j - 1])}); } } sort(g.begin(), g.end(), [](Node& a, Node& b) -> bool { return a.w < b.w; }); UnionFind uf(n * m); for (auto& p : g) { uf.unite(p.x, p.y); if (uf.connected(0, n * m - 1)) return p.w; } return 0; } };
|