classSolution{publicint[][]floodFill(int[][] image,int sr,int sc,int color){int initColor = image[sr][sc];// Base caseif(image[sr][sc]== color){return image;}// Fill the imagefill(image, sr, sc, initColor, color);return image;}privatevoidfill(int[][] image,int r,int c,int initColor,int color){// Check in boundif(!inBound(r, c, image))return;// Check if the same with initial colorif(image[r][c]!= initColor)return;// Fill the color
image[r][c]= color;// Fill the rest possible cellsfill(image, r +1, c, initColor, color);fill(image, r -1, c, initColor, color);fill(image, r, c +1, initColor, color);fill(image, r, c -1, initColor, color);}// Inside the boundaryprivatebooleaninBound(int r,int c,int[][] image){return r >=0&& r < image.length
&& c >=0&& c < image[0].length;}}
2023/12/02再次嘗試
這次自己20分鐘寫出來了,用的還是之前卡住的BFS
classSolution{publicint[][]floodFill(int[][] image,int sr,int sc,int color){// Base caseif(image[sr][sc]== color)return image;finalintM= image.length;finalintN= image[0].length;int sourceColor = image[sr][sc];Queue<int[]> q =newLinkedList<>();// 4 dimensionint[][] dims =newint[][]{{1,0},// up{-1,0},// down{0,-1},// left{0,1},// right};// Add the source
q.offer(newint[]{sr, sc});// Change the color of the source cell
image[sr][sc]= color;// BFSwhile(!q.isEmpty()){int[] cell = q.poll();// Check every dimensionfor(int[] dim : dims){// Checking neighboursint row = dim[0]+ cell[0];int col = dim[1]+ cell[1];if(inBound(M,N, row, col)&&
image[row][col]== sourceColor){// Change the color
image[row][col]= color;// Add to the queue
q.offer(newint[]{row, col});}}}return image;}privatebooleaninBound(intM,intN,int row,int col){return row >=0&& row <M&& col >=0&& col <N;}}