As Far from Land as Possible

ㅋㅋ·2023년 2월 10일
0

알고리즘-leetcode

목록 보기
107/135

정수형 2차원 벡터인 grid를 받는다. 물을 뜻하는 0과 땅을 뜻하는 1로 이루어져있는데

맨하탄 거리 |x0 - x1| + |y0 - y1|를 기준으로 물에서 땅까지 가장 멀 때 거리를 구하는 문제

class Solution {
public:
    int maxDistance(vector<vector<int>>& grid) {
        
        queue<pair<int, int>> waiting{};

        int length = grid.size();
        for (int y = 0; y < length; ++y)
        {
            for (int x = 0; x < length; ++x)
            {
                if (grid[y][x])
                {
                    waiting.push({x, y});
                }
            }
        }

        if (waiting.size() == length * length || waiting.empty())
        {
            return -1;
        }

        int counter{-1};
        while (waiting.empty() == false)
        {
            int left = waiting.size();
            for (int i = 0; i < left; ++i)
            {
                auto position{waiting.front()};
                waiting.pop();

                for (int j = 0; j < 4; ++j)
                {
                    int nextX{position.first + XDirection[j]};
                    int nextY{position.second + YDirection[j]};

                    if (nextX < 0 || nextY < 0 || nextX == length || nextY == length || grid[nextY][nextX])
                    {
                        continue;
                    }

                    grid[nextY][nextX] = 1;
                    waiting.push({nextX, nextY});
                }
            }

            ++counter;
        }

        return counter;
    }

private:
    const vector<int> XDirection{0, 0, -1, 1};
    const vector<int> YDirection{-1, 1, 0, 0};
};

0개의 댓글