|
์ฝ๋ ์์ฑํ๊ธฐ
#include<vector>
#include<queue>
#include<utility>
#include<algorithm>
using namespace std;
typedef pair<int, int>p;
queue<p>q;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int check[105][105];
int solution(vector<vector<int> > maps)
{
int answer;
int n = maps.size(), m = maps[0].size();
q.push({ 0,0 }); //bfs ์์
check[0][0] = 1;
while (!q.empty()) {
p now = q.front();
q.pop();
int x = now.first, y = now.second;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx < 0 || n <= nx || ny < 0 || m <= ny || !maps[nx][ny])continue;
if (!check[nx][ny]) {
check[nx][ny] = check[x][y] + 1;
q.push({ nx,ny });
}
}
}
answer = check[n - 1][m - 1];
return !answer ? -1 : answer;
}
C++
๋ณต์ฌ
|
์ฝ๋ ์ค๋ช
ํ๊ธฐ
์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ๋ ๊ทธ๋ํ ํ์ ๋ฌธ์
1.
0,0 ์์ ์ถ๋ฐ
2.
์, ํ, ์ข, ์ฐ๋ก ์์ง์ผ ์ ์๋ค๋ฉด ์์ง์ด๋ฉด์ 0,0์ผ๋ก๋ถํฐ ๊ฑฐ๋ฆฌ ๊ธฐ๋ก
a.
ex) (1, 0) ์์ (1, 1)๋ก ์์ง์๋ค๋ฉด (0, 0)์์ (1, 1)๊น์ง ๊ฑฐ๋ฆฌ = (0, 0)์์ (1, 0)๊น์ง ๊ฑฐ๋ฆฌ +1
3.
bfs๊ฐ ๋๋๋ฉด n-1, m-1๊น์ง ๊ฑฐ๋ฆฌ๋ฅผ ์ถ๋ ฅ
a.
๋๋ฌํ ์ ์๋ค๋ฉด -1 ์ถ๋ ฅ
b.
n๊ณผ m์ ๋ค๋ฅผ ์ ์๋ค