#include // for support of two-dimensional matrices #include // for basic input and output #include #include #include using namespace boost::numeric::ublas; using namespace std; void visualize(int curR, int curC, const matrix& comp, const std::vector >& fringe) { cout << "Visiting row " << curR << ", column " << curC << endl; for (int r = 0; r findComponent(const matrix& A, int r, int c, bool showVisualization=false) { // Basic two-dimensional array of integers int delta[][2] = { {-1, 0}, // up one row { 0, -1}, // left one column {+1, 0}, // down one row { 0, +1} // right one column }; int numRows = A.size1(); int numCols = A.size2(); matrix component(numRows, numCols); for (int row = 0; row < numRows; row++) for (int col = 0; col < numCols; col++) component(row,col) = false; component(r,c) = true; // starting location std::vector > fringe; // vector of (row,col) pairs fringe.push_back(make_pair(r,c)); // starting location while (!fringe.empty()) { // consider LAST entry of fringe r = fringe.back().first; c = fringe.back().second; if (showVisualization) visualize(r,c,component, fringe); // add ONE unvisited neighbor to the fringe (if any) int dir, option, newR, newC; dir = -1; // actual direction chosen option = 0; // possible direction to consider while (dir < 0 && option < 4) { newR = r + delta[option][0]; newC = c + delta[option][1]; if (newR >= 0 && newR < numRows && newC >= 0 && newC < numCols && A(newR,newC) == A(r,c) && !component(newR,newC)) dir = option; else option++; } if (dir >= 0) { // add neighbor to our fringe fringe.push_back(make_pair(newR,newC)); component(newR,newC) = true; } else { // last entry is a dead end fringe.pop_back(); } } return component; } int main() { int rows, cols, maxVal, startRow, startCol; cout << "How many rows? "; cin >> rows; cout << "How many columns? "; cin >> cols; cout << "Maximum value? "; cin >> maxVal; // pick random matrix of ints // srand( time(NULL) ); // seed random number generator based on clock time matrix sample(rows,cols); for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) sample(r,c) = 1 + (rand() % maxVal); // echo original matrix to the screen for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) cout << setw(3) << sample(r,c); cout << endl; } // what starting point? cout << endl << "You must pick a starting row and column (zero-indexed)." << endl; cout << "Starting row? "; cin >> startRow; cout << "Starting column? "; cin >> startCol; bool visualize = false; cout << "Do you want to see visualzation [y/n]? "; string yesNo; cin >> yesNo; if (yesNo[0] == 'y' || yesNo[0] == 'Y') visualize = true; matrix inComponent = findComponent(sample, startRow, startCol, visualize); // echo final component for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) if (inComponent(r,c)) cout << setw(3) << sample(r,c); else cout << " ."; cout << endl; } }