문제 링크입니다: https://school.programmers.co.kr/learn/courses/30/lessons/150365
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
사전순으로 가장 빠른 경로를 구해야 하므로 그리디 하게 [d, l, r, u] 순으로 백트래킹하면 되는 문제였습니다.
시간을 단축시키기 위해 현재 지점과 탈출 지점 사이의 맨해튼 거리를 구해 거리가 안될 경우 가지치기를 진행했습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <set> | |
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
typedef struct | |
{ | |
int y, x; | |
} Dir; | |
Dir moveDir[4] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}}; | |
char c[4] = {'d', 'l', 'r', 'u'}; | |
int N, M, K; | |
bool flag; | |
pair<int, int> target; | |
set<string> s; | |
void func(int y, int x, string text, int cnt) | |
{ | |
if (flag) | |
{ | |
return; | |
} | |
if (abs(y - target.first) + abs(x - target.second) > K - cnt) | |
{ | |
return; | |
} | |
if (cnt == K) | |
{ | |
if (y == target.first && x == target.second) | |
{ | |
s.insert(text); | |
flag = true; | |
} | |
return; | |
} | |
for (int k = 0; k < 4; k++) | |
{ | |
int nextY = y + moveDir[k].y; | |
int nextX = x + moveDir[k].x; | |
if (nextY < 1 || nextY > N || nextX < 1 || nextX > M) | |
{ | |
continue; | |
} | |
text += c[k]; | |
func(nextY, nextX, text, cnt + 1); | |
text.pop_back(); | |
} | |
} | |
string solution(int n, int m, int x, int y, int r, int c, int k) { | |
N = n, M = m, K = k; | |
target = {r, c}; | |
int len = abs(x - r) + abs(y - c); | |
if (len > k || (k - len) % 2) | |
{ | |
return "impossible"; | |
} | |
func(x, y, "", 0); | |
return (s.empty() ? "impossible" : *s.begin()); | |
} |

개발환경: Programmers IDE
지적, 조언, 질문 환영합니다! 질문 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers] 상담원 인원 (0) | 2024.05.08 |
---|---|
[Programmers] 표현 가능한 이진트리 (0) | 2024.05.08 |
[Programmers] 등산코스 정하기 (0) | 2024.05.07 |
[Programmers] 고고학 최고의 발견 (0) | 2024.05.07 |
[Programmers] 연도별 대장균 크기의 편차 구하기 (0) | 2024.04.07 |