Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 39080
- 재귀
- 코딩테스트
- 백트래킹
- 백준
- Java
- ElementTree
- 줄어드는 숫자
- 순열장난
- 백트렉킹
- 그래프
- 입실 퇴실
- 문서자동화
- 복서 정렬하기
- 위클리 6주차
- 위클리 챌린지
- 완전 탐색
- 너비우선탐색
- DP
- 부분 수열의 합
- 몯느 순열
- 10597
- 백트랙킹
- 좋은 수열
- dfs
- openssl
- 프로그래머스
- BOJ
- BFS
- 1174
Archives
개발자-H 입니다.
프로그래머스 - 게임 맵 최단 거리 본문
https://programmers.co.kr/learn/courses/30/lessons/1844
코딩테스트 연습 - 게임 맵 최단거리
[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1
programmers.co.kr
- 그래프 탐색 문제이다.
- DFS로 시도하였으나 시간 초과 및 반례가 있어 BFS로 변경하여 풀었다.
- 입력 형태가 맵 + BFS 요구 여서 인접 노드를 어떻게 탐색해야 하나 궁금했다
- move라는 배열로 이동 가능한 범주를 주어 인접 노드 탐색을 찾는 것으로 해결했다.
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int solution(int[][] maps) {
int answer = -1;
int goldR = maps.length - 1;
int goldC = maps[0].length - 1;
int[][] move = new int[][]{
{1, 0},
{-1, 0},
{0, 1},
{0, -1},
};
boolean[][] visited = new boolean[maps.length][maps[0].length];
Queue<State> queue = new LinkedList<>();
queue.offer(new State(0, 0, 1));
while (!queue.isEmpty()) {
State currentNode = queue.poll();
if (visited[currentNode.r][currentNode.c] == true) continue;
visited[currentNode.r][currentNode.c] = true;
if(currentNode.r == goldR && currentNode.c == goldC) {
answer = currentNode.depth;
break;
}
for (int i = 0; i < 4; i++) {
int nextR = currentNode.r + move[i][0];
int nextC = currentNode.c + move[i][1];
if (nextR >= maps.length || nextR < 0) continue;
if (nextC >= maps[0].length || nextC < 0) continue;
if (maps[nextR][nextC] == 1) {
queue.offer(new State(nextR, nextC, currentNode.depth + 1));
}
}
}
return answer;
}
}
class State {
public int r;
public int c;
public int depth; // 이동거리
public State(int r, int c, int depth) {
this.r = r;
this.c = c;
this.depth = depth;
}
}
'Algorithm > 문제 풀이' 카테고리의 다른 글
BOJ - 미로 탐색 (2178) (0) | 2021.08.09 |
---|---|
BOJ - 바이러스 (0) | 2021.08.08 |
프로그래머스 - 숫자 문자열과 영단어 (0) | 2021.08.08 |
프로그래머스 - 포멧몬 (0) | 2021.08.08 |
구름 - 길찾기 (다이아몬드) (0) | 2021.08.08 |