//"grid.h"
#ifndef GRID_H
#define GRID_H
#include <string>
#include <vector>
using namespace std;
const bool INFECTED = true;
const bool NOT_INFECTED = false;
class grid;
ostream &operator<<(ostream &stream, const grid& ob);
class grid {
private:
int rows;
int cols;
int number;
vector<bool> *area;
vector<bool>*area2;
int indexof (int row, int col) const;
bool infected(int row, int col) const;
void factorial(int row,int col);
public:
grid (string file);
~grid ();
int count (int row, int col);
friend ostream &operator<<(ostream &stream, const grid& ob);
};
#endif
//"grid.cpp"
#include <iostream>
#include <fstream>
using namespace std;
#include "grid.h"
// You do not need to alter function indexof.
int grid::indexof (int row, int col) const {
return row*cols+col;
}
// You do not need to alter function infected.
bool grid::infected(int row, int col) const {
return (area->operator[](indexof(row, col)) == INFECTED);
}
// You may need to alter the constructor
grid::grid (string file) {
number = 0;
// number to count the infected units
ifstream grid_file;
grid_file.open (file.c_str());
if(!grid_file)
cerr<<"Can't open the "<<file<<" file!"<<endl;
grid_file >> rows;
grid_file >> cols;
area = new vector<bool>(rows*cols, NOT_INFECTED);
area2 = new vector<bool>(rows*cols,NOT_INFECTED);
// a new vector catch the real infected units
while (true) {
int blob_row;
int blob_col;
grid_file >> blob_row;
grid_file >> blob_col;
if (grid_file.eof()) {
break;
}
area->operator[](indexof(blob_row,blob_col)) = INFECTED;
}
grid_file.close();
}
// You may need to alter the destructor
grid::~grid () {
delete area;
}
// You will need to alter this function to display the
// plus signs (+) next to the cells that belong to
// a counted colony.
ostream &operator<<(ostream &stream, const grid& ob) {
for (int row=0; row < ob.rows; row++) {
for (int col=0; col < ob.cols; col++) {
stream << ob.area->operator[](ob.indexof(row, col));
if(ob.area2 ->operator [](ob.indexof (row,col))==INFECTED)
stream<<"+ ";
else
stream << " ";
}
stream << endl;
}
stream << endl;
return stream;
}
// Replace the return statement in this function with your
// recursive implementation of this method */
int grid::count (int row, int col){
factorial(row,col);
return number;
//do the recursion function and return the number count the infected units
}
void grid::factorial(int row,int col){
if(row>=0 && row<=rows && col>=0 && col<=cols&&area2->operator [](indexof(row,col))==NOT_INFECTED){
if(infected(row,col)){
area2->operator [](indexof(row,col)) = INFECTED;
factorial(row,col+1);
factorial(row,col-1);
factorial(row+1,col);
factorial(row-1,col);
factorial(row+1,col+1);
factorial(row+1,col-1);
factorial(row-1,col+1);
factorial(row-1,col-1);
number++;
}
}
}
//the recursion function factorial to infect the units around the appointed unit