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?
答案 0 :(得分: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);
}
}