본문 바로가기

정리해두는거/알고리즘

미로 탐색

728x90
반응형
SMALL

https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

  • moveCnt를 증가시키고 확장을 하기 전에 큐의 size를 확인해서 진행했어야 한다
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

int row;
int col;

vector<string> maze;
vector<vector<bool>> visited;

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

void bfs()
{
    int moveCnt=0;
    queue<pair<int,int>> q;

    moveCnt++;
    visited[0][0] = true;
    q.push(make_pair(0,0));

    while(!q.empty())
    {
        size_t qsize = q.size();
        moveCnt++;
        for(int move=0; move<qsize; move++)
        {
            int curR = q.front().first;
            int curC = q.front().second;
            q.pop();

    
            for(int d=0; d < 4; d++)
            {
                int nextR = curR + dx[d];
                int nextC = curC + dy[d];

                if(nextR < 0 || nextR >= row || nextC < 0 || nextC >= col)
                {
                    continue;
                }

                if(maze[nextR].at(nextC) == '0' || visited[nextR][nextC] == true)
                {
                    continue;
                }

                if(nextR==row-1 && nextC==col-1)
                {
                    cout << moveCnt;
                    return;
                }

                visited[nextR][nextC] = true;            
                q.push(make_pair(nextR, nextC));
            }
        }
    }
}

int main()
{
    cin >> row >> col;

    maze.resize(row);
    visited.resize(row, vector<bool>(col, false));

    for(int i=0; i<row; i++)
    {
        cin >> maze[i];
    }

    bfs();
}

 

728x90
반응형
LIST

'정리해두는거 > 알고리즘' 카테고리의 다른 글

토마토  (0) 2024.02.18
설탕 배달 (dp)  (1) 2024.02.17
설탕 배달 (그냥 구현)  (0) 2024.02.17
마법사 상어와 파이어볼  (0) 2024.02.16
XCode에서 연습하게 되었다  (0) 2024.02.04