[프로그래머스] 게임 맵 최단거리(C++)

2025. 4. 15. 17:51·개발/알고리즘
728x90

 

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/1844

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

코드 구현

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct Point
{
    int y, x;
    
    Point operator+(const Point& other) const 
    {
        return Point(y + other.y, x + other.x);
    }

    bool operator==(const Point& other) const
    {
        if (y == other.y && x == other.x)
            return true;
        return false;
    }

    Point(int _y, int _x) 
        : y(_y)
        , x(_x) 
    {}
};

queue<Point> q;
vector<Point> direction = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };

int solution(vector<vector<int>> maps)
{
    int answer = 0;

    int height = maps.size();
    int width = maps[0].size();

    Point start = { 0, 0 };
    Point end = { height - 1, width - 1 };
    
    q.push(start);

    while (!q.empty())
    {
        // 큐에서 빼냄
        Point point = q.front();

        if (point == end)
        {
            answer = maps[point.y][point.x];
            return answer;
        }
        
        q.pop();

        // 인접한 타일 중, 갈 수 있는 타일 체크
        for (int i = 0; i < direction.size(); i++)
        {
            Point nextPoint = point + direction[i];
            if (nextPoint.y >= 0 && nextPoint.y < height && nextPoint.x >= 0 && nextPoint.x < width)
            {
                // 큐에 삽입, 방문 체크
                if (maps[nextPoint.y][nextPoint.x] == 1)
                {
                    q.push(nextPoint);
                    maps[nextPoint.y][nextPoint.x] += maps[point.y][point.x];
                }
            }
        }
        
    }

    return answer = -1;
}

 

 

해결 방법

BFS 알고리즘을 사용하여 맵 이동시 값을 1씩 증가시켜 도착하면 타일 안의 값을 반환(최솟값)

 

 

후기

좌표를 편하게 사용하기 위해 Point 구조체를 따로 만드느라 생난리를 쳤는데, 다른 사람 풀이를 참고하니 pair<> 구조체를 쓸 걸 그랬다.

'개발 > 알고리즘' 카테고리의 다른 글

[프로그래머스] 타겟 넘버(C++)  (1) 2025.04.19
[백준] 2606번: 바이러스(C++)  (2) 2025.04.18
[프로그래머스] 미로 탈출(C++)  (1) 2025.04.17
BFS 구현(C++)  (0) 2025.04.14
DFS 구현 (C++)  (0) 2025.04.14
'개발/알고리즘' 카테고리의 다른 글
  • [백준] 2606번: 바이러스(C++)
  • [프로그래머스] 미로 탈출(C++)
  • BFS 구현(C++)
  • DFS 구현 (C++)
Majangnan
Majangnan
  • Majangnan
    개발 모코코
    Majangnan
  • 전체
    오늘
    어제
    • 분류 전체보기 (81)
      • 개발 (80)
        • C# (10)
        • SQL (3)
        • Unity (9)
        • Unreal (10)
        • C++ (3)
        • Server (1)
        • DX11 (8)
        • 알고리즘 (35)
  • 블로그 메뉴

    • 홈
    • 방명록
    • 깃허브
  • 링크

    • 백준 허브
  • 공지사항

  • 인기 글

  • 태그

    DX11
    UnReal
    c++
    블루프린트
    슈팅게임
    MAC
    blueprint
    sql
    C#
    3dlight
    Unity
    알고리즘
    Mecanim
    상속
    백준
    DirectX11
    코딩테스트
    프로그래머스
    언리얼
    dx3d
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Majangnan
[프로그래머스] 게임 맵 최단거리(C++)
상단으로

티스토리툴바