Notice
Recent Posts
Recent Comments
Today
Total
01-10 22:06
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

WonderJay 2022. 7. 14. 09:16
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://school.programmers.co.kr/learn/courses/30/lessons/1844

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

BFS ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉด ๋˜๋Š”๋ฐ, dist ๋ฐฐ์—ด์„ ํ™œ์šฉํ•˜์—ฌ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ๋กœ๊นŒ์ง€ ์†Œ์š”๋˜๋Š” ์‹œ๊ฐ„(?)์„ ๊ธฐ๋กํ•œ๋‹ค. ์ด๋•Œ dist ๋ฐฐ์—ด์„ ์ดˆ๊ธฐ์— -1 ๋กœ ์„ค์ •ํ•˜๋ฉด visit ๋ฐฐ์—ด์„ ๋”ฐ๋กœ ๋‘์ง€ ์•Š๊ณ ๋„ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€ ์ฒดํฌ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

 

[C++]

#include <vector>
#include <queue>
#include <iostream>

using namespace std;

int dist[101][101];
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};

int solution(vector<vector<int> > maps)
{
    int answer = 0;
    // n x m ,  1 ~ n,m ~ 100
    // 0 : ๋ฒฝ  1 : ๊ธธ
    
    int n = maps.size(); int m = maps[0].size();
    
    for(int i = 0 ; i < n; i++)
        fill(dist[i], dist[i]+m, -1);
    
    queue<pair<int, int>> q;
    q.push({0, 0});
    dist[0][0] = 0;
    
    while(!q.empty())
    {
        pair<int, int> cur = q.front();
        q.pop();
        
        for(int dir = 0 ; dir < 4 ; dir ++)
        {
            int nx = cur.first + dx[dir];
            int ny = cur.second + dy[dir];
            
            if(nx<0 || nx>= n || ny<0 || ny>=m) continue; // out of bounds
            if(maps[nx][ny] == 0 || dist[nx][ny] > 0) continue;
            
            dist[nx][ny] = dist[cur.first][cur.second] + 1;
            q.push({nx, ny});
        }
        
    }
    
    answer = dist[n-1][m-1];
    return answer == -1 ? -1 : answer+1;
}

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments