Flood fill algorithm in JavaScript - too much recursion

China☆狼群 提交于 2019-12-13 06:47:52

问题


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?


回答1:


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);
  }
}


来源:https://stackoverflow.com/questions/36408961/flood-fill-algorithm-in-javascript-too-much-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!