0

So, I'm coding a Bejeweled clone and I have an error in my flood fill function. I have a 15 x 15 matrix of jewels of different color and I try to count the number of tiles with flood-fill.

The function is here:

function count(x, y, color) {

  if(matrix[x] && matrix[x][y]) {
    if(matrix[x][y].color != color)
      return;
    cnt++;
    count(x, y+1, color);
    count(x, y-1, color);
    count(x-1, y, color);
    count(x+1, y, color);
    console.log(cnt);
  }
}

What's wrong?

mkkekkonen
  • 1,704
  • 2
  • 18
  • 35
  • Interesting. At a guess I'd say you are counting the same cells over and over again ... first the one on its right, then *its* one on its left, then `GO TO start` and so on. – Jongware Apr 04 '16 at 17:22
  • You dont recolor the cells you visited, you get into an infinite recursion. – Tamas Hegedus Apr 04 '16 at 17:22
  • @Chara bounds are checked by the two first logical expressions in the if condition – axelduch Apr 04 '16 at 17:24

1 Answers1

3

It looks like your problem is that your function isn't distinguishing between squares that have been counted and squares that haven't. So adjacent squares will keep counting each other.

One solution is to work off of a copy of your grid, and modify the color of the visited squares so they won't get counted again. Alternatively, you could add a counted property to each cell, and set it when you count the cell, and return if you're trying to count a cell that's already been counted. Then just make sure to reset the counted properties once you're done.

Something like:

function count(x, y, color) {

  if(matrix[x] && matrix[x][y]) {
    if(matrix[x][y].color != color || matrix[x][y].counted)
      return;
    cnt++;
    matrix[x][y].counted = true;
    count(x, y+1, color);
    count(x, y-1, color);
    count(x-1, y, color);
    count(x+1, y, color);
    console.log(cnt);
  }
}
StephenTG
  • 2,579
  • 6
  • 26
  • 36
  • 1
    I added a `matrix[x][y].counted` property and set it to true when the tile has been counted, that works. Then I reset it after the `cnt` value has been processed. – mkkekkonen Apr 04 '16 at 17:28
  • Yeah, that also works. I'll add that to my answer in case anyone else with this problem comes along – StephenTG Apr 04 '16 at 17:29