64,692
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
typedef struct node
{
int data;// 0 for island 1 for pond
bool visited;
}node;
void recMark(node **Matrix, int y, int x, int flag)//rec find and mark
{
Matrix[y][x].visited = true;
if(Matrix[y-1][x].data = flag)
recMark(Matrix, y-1, x, flag);
if(Matrix[y][x+1].data = flag)
recMark(Matrix, y, x+1, flag);
if(Matrix[y+1][x].data = flag)
recMark(Matrix, y+1, x, flag);
if(Matrix[y][x-1].data = flag)
recMark(Matrix, y, x-1, flag);
}
void loopFind(node **Matrix, int y , int x)//y and x represent the size of the matrix
{
int pondCounts = 0;
int islandCounts = 0;
for(int _y = 1; _y <= y-2; _y++ )
{
for(int _x = 1; _x <= x-2 ; _x++)
{
if(Matrix[_y][_x].visited == false)//if not visited, then visit all related
{
if(Matrix[_y][_x].data == 0)
{
recMark(Matrix, _y, _x, 0);
pondCounts++;
}
else if(Matrix[_y][_x].data == 1)
{
recMark(Matrix, _y, _x, 1);
islandCounts++;
}
}
}
}
cout<<"the number of pond: "<<pondCounts<<", and the number of island(s): "<<islandCounts<<endl;
//return tolCounts;
}
int main()
{
ifstream fin;
fin.open("PondsIslands.txt");
if(!fin)
{
cout<<"opening file failed"<<endl;
exit(-1);
}
int x =0;
int y =0;
while(!fin.eof())
{
fin>>y>>x;
node theMatrix[y+2][x+2];
for(int _x = 0;_x<x+2; _x++ )
{
for(int _y = 0; _y< y+2; _y++ )
{
theMatrix[y][x].visited = false; // mark un-visited
}
}
//setting the surrounding to 9 to signify edging
for(int temp = 0; temp < x+2; temp++)
{
theMatrix[0][temp].data = 9;
theMatrix[y+1][temp].data = 9;
}
for(int temp = 0; temp < y+2; temp++)
{
theMatrix[temp][0].data = 9;
theMatrix[temp][x+1].data = 9;
}
//putting all the number 0 or 1 into the inner of array
for(int tempY = 1; tempY <= y; tempY++)
{
for(int tempX = 1; tempX<= x; tempX++)
{
string stemp;
getline(fin, stemp);
stringstream sstemp(stemp);
sstemp>>theMatrix[tempX][tempY].data;
}
}
//cout<<"reach here "<<endl;
}
fin.close();
return 0;
}