0% found this document useful (0 votes)
1 views

lab7 Q1.cpp

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

lab7 Q1.cpp

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <vector>
#include <stdexcept>

class Percolation {
private:
int n;
std::vector<bool> openSites;
std::vector<int> parent;
std::vector<int> size;
int virtualTop;
int virtualBottom;
int openCount;

int index(int row, int col) const {


return row * n + col;
}

int root(int i) {
while (i != parent[i]) {
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}

void unionSites(int p, int q) {


int rootP = root(p);
int rootQ = root(q);
if (rootP == rootQ) return;
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
} else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
}

bool connected(int p, int q) {


return root(p) == root(q);
}

public:
Percolation(int n) : n(n), openSites(n * n, false), parent(n * n + 2), size(n *
n + 2, 1), openCount(0) {
if (n <= 0) throw std::invalid_argument("Grid size must be positive");
virtualTop = n * n;
virtualBottom = n * n + 1;
for (int i = 0; i < n * n + 2; ++i) {
parent[i] = i;
}
}

void open(int row, int col) {


if (row < 0 || row >= n || col < 0 || col >= n) throw
std::invalid_argument("Invalid row or column");
int idx = index(row, col);
if (openSites[idx]) return;
openSites[idx] = true;
openCount++;
if (row > 0 && isOpen(row - 1, col)) unionSites(idx, index(row - 1, col));
if (row < n - 1 && isOpen(row + 1, col)) unionSites(idx, index(row + 1,
col));
if (col > 0 && isOpen(row, col - 1)) unionSites(idx, index(row, col - 1));
if (col < n - 1 && isOpen(row, col + 1)) unionSites(idx, index(row, col +
1));
if (row == 0) unionSites(idx, virtualTop);
if (row == n - 1) unionSites(idx, virtualBottom);
}

bool isOpen(int row, int col) const {


if (row < 0 || row >= n || col < 0 || col >= n) throw
std::invalid_argument("Invalid row or column");
return openSites[index(row, col)];
}

bool isFull(int row, int col) {


if (row < 0 || row >= n || col < 0 || col >= n) throw
std::invalid_argument("Invalid row or column");
return connected(index(row, col), virtualTop);
}

int numberOfOpenSites() const {


return openCount;
}

bool percolates() {
return connected(virtualTop, virtualBottom);
}

static void test() {


Percolation p(3);
p.open(0, 0);
std::cout << "Percolates? " << p.percolates() << std::endl;
p.open(1, 0);
p.open(2, 0);
std::cout << "Percolates? " << p.percolates() << std::endl;
}
};

int main() {
Percolation::test();
return 0;
}

You might also like