๐ป ์ฝ๋ฉ ํ
์คํธ C++/ํ๋ก๊ทธ๋๋จธ์ค
[ํ๋ก๊ทธ๋๋จธ์ค] ๊ฒ์ ๋งต ์ต๋จ๊ฑฐ๋ฆฌ
์ซ๋
2023. 12. 18. 22:18
https://school.programmers.co.kr/learn/courses/30/lessons/1844
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
int check[101][101];
int dy[] = {-1, 0, 1, 0};
int dx[] = {0, 1, 0, -1};
int solution(vector<vector<int>> maps)
{
int n, m;
n = maps.size();
m = maps[0].size();
queue<pair<int, int>> q;
// ์ถ๋ฐ์ง๋ ์์ฝ ์์
์ ํ ์ ์๊ณ ๋ฐ๋ก ๋ฐฉ๋ฌธํด์ผ ํ๋ ๋ฏธ๋ฆฌ ์์
q.push(make_pair(0, 0)); // ํ์ ๋ฃ๊ธฐ
check[0][0] = true; // ์์ฝ ๊ณผ์
while(!q.empty()){ // ๊ผญ ์ฒดํฌํด์ฃผ๊ธฐ!
// ๋ฐฉ๋ฌธ ๊ณผ์
int x = q.front().first;
int y = q.front().second;
q.pop();
// ์์ฝ ๊ณผ์ : ๋ฐฉ๋ฌธํ ๊ณณ์ ๊ธฐ์ค์ผ๋ก ์๊ณ๋ฐฉํฅ์ผ๋ก ์-์ฐ-ํ-์ข ์์ฝํ๊ธฐ
for(int i=0; i<4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
// ๋ฐฉ๋ฌธ ๊ฐ๋ฅํ ์ง, ์ฆ ์์ฝ ๊ฐ๋ฅํ์ง๋ฅผ ์ฒดํฌ
if(0<=nx && nx<n && 0<=ny && ny<m){
if(check[nx][ny] == false && maps[nx][ny] > 0){
check[nx][ny] = true;
maps[nx][ny] = maps[x][y] + 1;
q.push(make_pair(nx, ny));
}
}
}
}
int answer = 0;
if(maps[n-1][m-1] == 1){
answer = -1;
}else{
answer = maps[n-1][m-1];
}
return answer;
}