본문 바로가기

내 맘대로 알고리즘/LeetCode 2020 May

May LeetCoding Challenge[Day11] - Flood Fill

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).

Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.

To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

At the end, return the modified image.
Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]

Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.

1. 알고리즘을 해결하기 위해서 생각한 방법

 

 - 힝... 글이 너무 많다.

 - 주어진 input과 output을 보고 문제를 이해하려고 했다.

 - image 배열이 주어질 때, sr과 sc에는 row, col의 위치가 담겨져있다. 이 때, 해당 픽셀을 newColor로 바꾸고, 주변도 newColor로 바꿀 때, 상하좌우로 newColor를 변경시킨다. 만약 그렇지 않다면 바꾸지 않는다.

 

2. 알고리즘 작성 중, 어려운 점

 

 - 좀 더 명확하게 알고리즘을 짜고 싶다.

 

3. 내가 작성한 알고리즘

 

 

class Solution {
    //[[1,1,1]
    // [1,1,0]
    // [1,0,1]]
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int memory[][] = new int[image.length][image[0].length];
        explore(image,memory, image[sr][sc], sr,sc , newColor);
        return image;
    }
    
    private void explore(int image[][], int memory[][], int target, int x, int y, int newColor){
        if(x < 0 || y < 0 || x >= image.length || y>= image[x].length){
            return;
        }
        
        if(memory[x][y]==1){
            return;
        }
        if(image[x][y] != target){
            memory[x][y] = 1;
            return;
        }
        if(image[x][y] == target){
            memory[x][y] = 1;
            image[x][y] = newColor;
            
            explore(image, memory, target, x-1, y, newColor);
            explore(image, memory, target, x, y-1, newColor);
            explore(image, memory, target, x+1, y, newColor);
            explore(image, memory, target, x, y+1, newColor);
        }
        
    }
}

4. 내가 작성한 알고리즘 결과

 

 

 

문제 : https://leetcode.com/explore/featured/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3326/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com