bfs/dfs

jimmy neutron·2023년 2월 1일
0

알고리즘

목록 보기
3/3

기본 유형

const floodFill2 = (image, sr, sc, newColor, firstColor = image[sr][sc]) => {
  if (
    sr < 0 ||
    sc < 0 ||
    sr >= image.length ||
    sc >= image[sr].length ||
    image[sr][sc] !== firstColor ||
    image[sr][sc] === newColor
  ) {
    return image; 
  }

  image[sr][sc] = newColor;

  floodFill(image, sr + 1, sc, newColor, firstColor);
  floodFill(image, sr - 1, sc, newColor, firstColor);
  floodFill(image, sr, sc + 1, newColor, firstColor);
  floodFill(image, sr, sc - 1, newColor, firstColor);

  // return modified image
  return image;
};

통과가 안되는 조건을 먼저 작성해서 리턴 조건을 설정해준 다음 재귀를 돌리는 형식이 기본으로 쓰인다.

profile
프론트엔드로 지구정복

0개의 댓글