I am having a lot of trouble with a Divide and Conquer algorithm to count the number of white cells and white cell blocks in a grid of black and white cells.
Here is my grid file "cells.txt":
w = white cell
b = black cell
bbbbbbbbbb
bwwwwwbwwb
bbbbbwbwwb
bwwwbbwwwb
bwbwbwwbbb
bwbwwwbwbb
bwbbbbwwwb
bwbwbbwwwb
bwbwbbwwwb
bbbbbbbbbb
Here is the code I have so far:
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_ROWS = 10;
const int MAX_COLS = 10;
class Cells
{
public:
Cells();
void count(int valueRow, int valueCol, int valueBlock, int valueCells);
private:
int block;
int size;
int row;
int col;
char map[MAX_ROWS][MAX_COLS];
};
Cells::Cells()
{
ifstream fin;
fin.open("cells.txt");
char ch;
int row = 0;
int col = 0;
if (fin.is_open())
{
while(fin.get(ch))
{
if(ch == '\n')
{
row = row + 1;
col = 0;
}
else
{
map[row][col] = ch;
col = col + 1;
}
}
}
else
{
cout << "Unable to open file for reading." << endl;
}
for (int i = 0; i < MAX_ROWS; ++i)
{
for (int j = 0; j < MAX_COLS; ++j)
{
cout << map[i][j];
}
cout << endl;
}
}
void Cells::count(int valueRow, int valueCol, int vaueBlock, int valueSize)
{
// mark current cell as visited.
map[valueRow][valueCol] = 'v';
if(map[valueRow][valueCol + 1] != 'b' || map[valueRow][valueCol + 1] != 'v')
{
count(valueRow, valueCol + 1, block, size + 1);
}
if(map[valueRow][valueCol - 1] != 'b' || map[valueRow][valueCol - 1] != 'v')
{
count(valueRow, valueCol - 1, block, size + 1);
}
if(map[valueRow + 1][valueCol] != 'b' || map[valueRow + 1][valueCol] != 'v')
{
count(valueRow + 1, valueCol, block, size + 1);
}
if(map[valueRow - 1][valueCol] != 'b' || map[valueRow - 1][valueCol] != 'v')
{
count(valueRow - 1, valueCol, block, size + 1);
}
cout << "Block: " << block << "has size: " << size << endl;
}
Here is the main program as well:
#include <iostream>
#include "Cells.h"
using namespace std;
int main()
{
Cells c;
// start at position 1,2 on the map which should be a white cell.
c.count(1, 2, 0, 0);
return 1;
}
On paper I feel like my algorithm should work. However, it is not working. It keeps throwing a stack overflow which I have been entirely unable to find a solution for. I am getting the feeling my algorithm is probably flawed, but I cannot see why it is. If someone could point me in the right direction or show me what the heck is going wrong I would be really grateful. In the meantime I am going to continue plugging away.