⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 grid.cpp

📁 本程序给出了SSD5实验课中Optional Exercise3的参考程序 内附有详细的注释 下载后请仔细参照源代码进行分析 切莫完全搬照
💻 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) {

	num = 0;
	
	
	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);
	flag_area = new vector<bool>(rows*cols,false);
	
	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.flag_area->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)
{

	caculate(row,col);
    return num;
}
void grid::caculate(int row,int col)
{
	if(row >= 0 && col >= 0 && row < rows && col < cols
		&& !flag_area->operator [](indexof(row,col)))
	{
		
		if(infected(row,col))
		{
			flag_area->operator [](indexof(row,col)) = true;
			num++;
			caculate(row,col+1);
			caculate(row+1,col+1);
			caculate(row+1,col);
			caculate(row+1,col-1);
			caculate(row,col-1);
			caculate(row-1,col-1);
			caculate(row-1,col);
			caculate(row-1,col+1);
			return;
		}
	}
	return;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -