#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;
ifstream grid_file;
//open the file
grid_file.open ("sample.grid");
//fail to open
if(!grid_file)
cerr<<"Can't open the file! The file is not exist!"<<endl;
grid_file >> rows;
grid_file >> cols;
area = new vector<bool>(rows*cols, NOT_INFECTED);
n_area = new vector<bool>(rows*cols, NOT_INFECTED);
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;
delete n_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 really infected,add a "+" after
if(ob.n_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) {
factorial(row,col);
return number;
}
//recursion function to simulate the infecting of units around the appointed unit
void grid::factorial(int row, int col)
{
if(row>=0 && row< rows && col>=0 && col< cols && n_area->operator [](indexof(row,col)) == NOT_INFECTED)
{
if(infected(row,col))
{
n_area->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++;
}
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
SSD5,Optional Exercise 3
共3个文件
cpp:2个
h:1个
4星 · 超过85%的资源 需积分: 6 73 下载量 113 浏览量
2009-11-27
16:35:11
上传
评论
收藏 2KB RAR 举报
温馨提示
是SSD5的Optional Exercise 3,正确无误,是递归函数的运用,很有帮助
资源推荐
资源详情
资源评论
收起资源包目录
Optional Exercise 3.rar (3个子文件)
Optional Exercise 3
main.cpp 795B
grid.h 1KB
grid.cpp 2KB
共 3 条
- 1
资源评论
- xenia2072012-11-08不错的答案,执行效率高。注释……
- Moon_魔宽2011-11-17不错的答案,执行效率高。只是缺少一些注释。
- Xianda_Chen2011-11-17不错的答案,执行效率高。注释和风格也不太完善
- mixiaopa2011-11-05变量有点小问题,注释和风格也不太完善
Dluolong
- 粉丝: 1
- 资源: 18
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功