일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 세브란스
- 카카오인턴십
- 부주상골증후군
- 독학
- 롯데정보통신
- 부주상골수술후기
- BFS
- DFS
- 스택
- 코테
- 부주상골
- SWIFT
- 분할정복
- ChatGPT
- dp
- 구현
- sql
- 카카오코테
- 독일어
- IOS
- 카카오인턴
- 부주상골수술
- c++
- 백준
- istringstream
- 프로그래머스
- 코딩테스트
- 독일어독학
- 리눅스
- SQLD
Archives
- Today
- Total
슈뢰딩거의 고등어
level 2 게임 맵 최단거리 (BFS) 본문
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
#include <iostream>
#include<vector>
#include<queue>
using namespace std;
struct POSI {
int y, x, t;
};
// BFS
vector<vector<int> > arr;
int answer = 987654321;
// x, y
int n, m;
const int dy[4] = {0, 0, -1, 1};
const int dx[4] = {-1, 1, 0, 0};
bool visit[110][110];
queue <POSI> q;
void BFS(POSI start) {
q.push(start);
visit[start.y][start.x] = true;
while(!q.empty()) {
POSI cur = q.front();
q.pop();
if(cur.y == m-1 && cur.x == n-1) {
answer = cur.t;
return;
}
for(int i=0; i<4; i++) {
POSI next;
next.y = cur.y + dy[i];
next.x = cur.x + dx[i];
next.t = cur.t + 1;
if(next.y < 0 || next.y >= m || next.x < 0 || next.x >= n)
continue;
if(visit[next.y][next.x] == false && arr[next.y][next.x] == 1) {
visit[next.y][next.x] = true;
q.push(next);
}
}
}
}
int solution(vector<vector<int> > maps)
{
arr = maps;
m = maps.size(); // y
n = maps[0].size(); // x
POSI start;
start.y = 0; start.x = 0; start.t = 1;
BFS(start);
if (answer == 987654321)
return -1;
return answer;
}
BFS 로 최단거리 풀기.
DFS 는 처음으로 나온 값이 최단 경로라는 확신이 없음.
-> 시간복잡도를 줄일 수 있음
처음 DFS 로 접근했다가 효율성 테스트 통과 실패
'알고리즘' 카테고리의 다른 글
17143 낚시왕 (0) | 2021.12.09 |
---|---|
19237 어른상어 (0) | 2021.12.08 |
level 2 소수찾기 -순열 (algorithm :: next_permutaion) (0) | 2021.12.06 |
19236 청소년상어 (cstring :: memcpy) (0) | 2021.12.06 |
16236 아기상어 (0) | 2021.12.05 |
Comments