[C++] 프로그래머스 미로 탈출 명령어

2024. 1. 3. 12:40·Algorithm/Programmers
#include <string>
#include <vector>

using namespace std;

string answer = "";

void dfs(int n, int m, int x, int y, int r, int c, int k, int currCount, string currPath)
{
    int manhattanRange = abs(x - r) + abs(y - c);                    
    if (manhattanRange + currCount > k)
    {        
        return;
    }
    if (x == r && y == c && k == currCount)
    {
        answer = currPath;
        return;
    }
    if(answer != "")
    {
        return;
    }

    if (x + 1 <= n)
    {
        dfs(n, m, x + 1, y, r, c, k, currCount + 1, currPath + 'd');
    }
    if (y - 1 >= 1)
    {
        dfs(n, m, x, y - 1, r, c, k, currCount + 1, currPath + 'l');
    }
    if (y + 1 <= m)
    {
        dfs(n, m, x, y + 1, r, c, k, currCount + 1, currPath + 'r');
    }
    if (x - 1 >= 1)
    {
        dfs(n, m, x - 1, y, r, c, k, currCount + 1, currPath + 'u');
    }
    
}


string solution(int n, int m, int x, int y, int r, int c, int k) 
{    
    int manhattanRange = abs(x - r) + abs(y - c);                    
    if ((k - manhattanRange) % 2 != 0)
    {        
        answer = "impossible";
    }
    else
    {
        dfs(n, m, x, y, r, c, k, 0, "");
    }
    
    if (answer == "")
    {
        answer = "impossible";
    }

    return answer;
}

 

풀이

1. 사전순으로 DFS를 하여 (d,l,r,u 순으로 탐색) 정렬할 필요없이 첫 번째로 나온 답이 답일 수 있도록 탐욕적으로 해결

2. 각 이동 시마다 맨해튼거리(현재 위치에서 도착점까지의 거리)를 측정하여 현재 위치에서 얼마나 걸리는지 확인

3. 현재 위치와 도착점, 이동한 거리가 같을 경우 정답으로 처리하고 남은 DFS들은 return 처리

4. 처음 시작점에서, 맨해튼거리와 k의 차가 홀수일 경우 도달할 수 없으므로 미리 불가능 처리

 

 

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

저작자표시 (새창열림)

'Algorithm > Programmers' 카테고리의 다른 글

[C++] 프로그래머스 과제 진행하기  (1) 2024.02.09
[C++] 프로그래머스 가장 많이 받은 선물  (1) 2024.01.11
[C++] 프로그래머스 거리두기 확인하기  (0) 2023.12.29
[C++] 프로그래머스 2016년  (0) 2022.03.05
[C++] 프로그래머스 정수삼각형  (0) 2021.12.31
'Algorithm/Programmers' 카테고리의 다른 글
  • [C++] 프로그래머스 과제 진행하기
  • [C++] 프로그래머스 가장 많이 받은 선물
  • [C++] 프로그래머스 거리두기 확인하기
  • [C++] 프로그래머스 2016년
chanheess
chanheess
'왜' 그렇게 했는가?에 대한 생각으로 공부 및 작업의 저장관리
  • chanheess
    왜 그렇게 생각했는가?
    chanheess
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Backend Programming
      • Game Programming
        • Unreal
        • DirectX
      • C++
        • Memo
        • Basic
        • Effective Modern
      • Algorithm
        • Memo
        • Baekjoon
        • Programmers
        • HackerRank, LeetCode
      • Data Structure
      • Design Pattern
      • Etc
        • Memo
        • Daily Log
        • Book
  • 최근 글

  • 최근 댓글

  • 태그

    dfs
    티스토리챌린지
    c++ 기초 플러스
    dp
    JPA
    spring
    알고리즘
    백준
    오블완
    프로그래머스
    JWT
    Java
    SpringSecurity
    위클리 챌린지
  • hELLO· Designed By정상우.v4.10.0
chanheess
[C++] 프로그래머스 미로 탈출 명령어
상단으로

티스토리툴바