✅ LV. 2
🔖 BFS
DFS
로 접근
Out Of Index
처리return
answer
갱신DFS
로 접근할 경우, 경로를 찾아갈 수는 있지만 최단거리를 구하는 방법에 적합한지는 잘 모르겠음.BFS
로 접근
풀이 방식은 DFS
와 유사하지만 큐를 사용해서 풀이
(0,0) push
dist
) 저장 ➡️ dist
에 저장한 값이 0
이 아니라면 방문했던 노드로 판단큐 empty
시점까지 계속 반복
front
인덱스를 현재 위치로 저장하고 pop
push
push
한 인덱스의 dist
값을 현재 위치의 dist
값에 1을 더해 저장해둠🔗 [C++] 큐
#include<vector>
#include <queue>
using namespace std;
int solution(vector<vector<int> > maps)
{
int answer = 0;
int cnt=1;
int dist[10000][10000];
queue<pair<int,int>> q;
q.push(make_pair(0,0));
dist[0][0]=cnt;
int mov[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
while(!q.empty()) {
int y=q.front().first;
int x=q.front().second;
if(y==maps.size()-1&&x==maps[0].size()-1) {
if(answer==0) answer=dist[y][x];
else answer=min(answer,dist[y][x]);
}
q.pop();
cnt=dist[y][x];
for(int i=0;i<4;i++) {
int yq=y+mov[i][0];
int xq=x+mov[i][1];
if(yq<0||xq<0||yq>=maps.size()||xq>=maps[0].size()) continue;
if(dist[yq][xq]==0 && maps[yq][xq]==1) {
q.push(make_pair(yq,xq));
dist[yq][xq]=++cnt;
}
}
}
if(answer==0) answer=-1;
return answer;
}
자꾸 효율성 오류가 난다,,거의 통과 못함
out of index
처리도 일단 다음 노드로 이동한 후에 처리하던가 애초에 이동조차 못하게 사전 방지하던가 한가지로 통일이 필요dist
를 배열로 구현했더니 메모리 낭비가 발생하는 것으로 보여서 벡터로 변환#include<vector>
#include <queue>
using namespace std;
int solution(vector<vector<int> > maps)
{
int answer = 0;
queue<pair<int,int>> q;
q.push(make_pair(0,0));
int yy=maps.size();
int xx=maps[0].size();
vector<vector<int> > dist(yy, vector<int>(xx, 0));
dist[0][0]=1;
int mov[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
while(!q.empty()) {
int y=q.front().first;
int x=q.front().second;
q.pop();
for(int i=0;i<4;i++) {
int yq=y+mov[i][0];
int xq=x+mov[i][1];
//Out of idx
if(yq<0||xq<0||yq>=yy||xq>=xx) continue;
//이미 지난 경로이거나 벽일 경우
if(maps[yq][xq]==0 || dist[yq][xq]>0) continue;
q.push(make_pair(yq,xq));
dist[yq][xq]=dist[y][x]+1;
}
}
if(dist[yy-1][xx-1]==0) return -1;
else return dist[yy-1][xx-1];
}