Level:easy
Topic: Array、DFS、BFS、Matrix
Description
拿到一個image陣列,image[i][j] 代表image 的pixel值,還有sr、sc、color, 從 image[sr][sc] 出發將其他像素顏色與 image[sr][sc] 相同染色成 color 直到不能再染色(超出範圍或顏色不等於image[sr][sc])。
Solution
使用DFS從image[sr][sc]開始擴散至不能染色為止。
/** * @param {number[][]} image * @param {number} sr * @param {number} sc * @param {number} color * @return {number[][]} */ var floodFill = function (image, sr, sc, color) { if (image[sr][sc] === color) return image; const rowLength = image.length; const colLength = image[0].length; const dir = [ [-1, 0], [1, 0], [0, 1], [0, -1], ]; const originColor = image[sr][sc]; var fun = function (x, y) { if (x < 0 || x >= rowLength || y < 0 || y >= colLength) return null; if (image[x][y] === originColor) { image[x][y] = color; fun(x + dir[0][0], y + dir[0][1]); fun(x + dir[1][0], y + dir[1][1]); fun(x + dir[2][0], y + dir[2][1]); fun(x + dir[3][0], y + dir[3][1]); } }; fun(sr, sc); return image; };