javascript - How can I optimize this floodFill algorithm? Advice needed -
i have fiddle following code. colorwalk clone
here js code:
function floodfill(x, y, selectedcolor, graycolor) { if (x < 0 || x >= 600) return; if (y < 0 || y >= 400) return; let square = $('.blockattribute').filter(function(ind, el) { return $(el).css('left') == x + 'px' && $(el).css('top') == y + 'px' }); let squarecolor = square.css('background-color'); if (squarecolor === graycolor || squarecolor === selectedcolor) { square.removeclass().addclass('blockattribute gray'); floodfill(x + 20, y, selectedcolor, graycolor); floodfill(x, y + 20, selectedcolor, graycolor); floodfill(x - 20, y, selectedcolor, graycolor); floodfill(x, y - 20, selectedcolor, graycolor); } else { return; } }
i've been working on learning javascript/jquery , algorithms , i've pretty have clone working except fact when deeper , deeper grid, slower , slower code is. i've been reading memoization , trying use on grid i'm getting stuck how approach. i'm looking little push regarding how this. maybe memoization isn't way go , maybe can optimize code other way. current thinking need grab last gray square , proceed there. on right track?
----edit------
i realized can combine if/else
operator check matching gray color or selected color
reading , writing dom expensive in javascript. should never use dom source of data.
to speed algorithm, store pixel data offline regular javascript data, manipulate data only, update visual code once. way minimize number of dom operations.
additionally, javascript not "tail call optimized," meaning can't recurse forever, , every level of recursion slow down program degree. if can use non-recursive flood fill algorithm in case, faster.
Comments
Post a Comment