언어 정리/c#

LeetCode - 733번 문제 bfs를 통한 해결

rimugiri 2024. 1. 2. 18:07
728x90
public class Solution
{
    private Point[] dirs = new Point[] { new Point(-1, 0), new Point (1, 0), new Point (0, -1), new Point (0, 1) };
    struct Point
    {
        public int X;
        public int Y;

        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }
    }

    public int[][] FloodFill(int[][] image,int sr, int sc, int color)
    {
    	//if 구문을 통해 무한 루프에 빠지는 것을 방지해 줘야 된다
        //color와 처음 부분이 같을 경우 무한루프에 빠지게 된다
    	if (image[sr][sc] == color) 
            return image;
        int y = sr;
        int x = sc;
        int startColor = image[y][x];
        Stack<Point> stack = new Stack<Point>();
        stack.Push(new Point(x,y));
        image[y][x] = color;

        while (stack.Count > 0)
        {
            Point curPoint = stack.Pop();
            foreach (Point dir in dirs)
            {
                int nextPointX = curPoint.X - dir.X;
                int nextPointY = curPoint.Y - dir.Y;

                if(nextPointX < image[0].Length && nextPointX >= 0 && nextPointY < image.Length && nextPointY >= 0)
                {
                    if (image[nextPointY][nextPointX] == startColor)
                    {
                        image[nextPointY][nextPointX] = color;
                        stack.Push(new Point(nextPointX, nextPointY));
                    }
                }
            }
        }
        return image;
    }
}

 

처음 좌표에 있는 image가 color와 같으면 무한 루프에 빠지게 되는 경우를 생각하지 않아 많은 시간을 소비하다.
겨우겨우 이 사실을 발견하게 되어 문제를 해결 할 수 있었다.
다시는 이러한 상황이 발생하지 않을만큼 내 머리속에 각인되어 버렸다.

728x90

'언어 정리 > c#' 카테고리의 다른 글

[c#] Console 다룰 때 알아두면 좋은 기능  (1) 2024.01.06
LeetCode - 300(동적 프로그래밍)  (1) 2024.01.02
C# - StringBulider  (0) 2023.12.29
c# - lambda 간단한 사용예제  (0) 2023.11.26
C# - delegate 확장 Func, Action  (1) 2023.11.26