문제 설명
게임 맵의 상태 maps가 매개변수로 주어질 때, 캐릭터가 상대 팀 진영에 도착하기 위해서 지나가야 하는 칸의 개수의 최솟값을 return 하도록 solution 함수를 완성해주세요. 단, 상대 팀 진영에 도착할 수 없을 때는 -1을 return 해주세요.제한 사항
maps는 n x m 크기의 게임 맵의 상태가 들어있는 2차원 배열로, n과 m은 각각 1 이상 100 이하의 자연수입니다.
n과 m은 서로 같을 수도, 다를 수도 있지만, n과 m이 모두 1인 경우는 입력으로 주어지지 않습니다.
maps는 0과 1로만 이루어져 있으며, 0은 벽이 있는 자리, 1은 벽이 없는 자리를 나타냅니다.
처음에 캐릭터는 게임 맵의 좌측 상단인 (1, 1) 위치에 있으며, 상대방 진영은 게임 맵의 우측 하단인 (n, m) 위치에 있습니다.입출력 예
maps : [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]]
answer : 11
maps : [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]]
answer : -1
BFS를 사용하는 문제
#include <string> #include <vector> #include <queue> using namespace std; vector<vector<int>> board; struct Cell { int _x; int _y; int _dist; Cell(int x, int y, int dist = 1) : _x(x), _y(y), _dist(dist) {} }; bool CanGo(int x, int y, const vector<vector<bool>>& visited) { if (x < 0 || x >= board.size()) return false; if (y < 0 || y >= board[0].size()) return false; if (visited[x][y]) return false; if (board[x][y] == 0) return false; return true; } int BFS(Cell start, Cell target) { int n = board.size(); int m = board[0].size(); vector<vector<bool>> visited(n, vector<bool>(m, false)); queue<Cell> q; q.push(start); visited[start._x][start._y] = true; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; while (!q.empty()) { Cell cur = q.front(); q.pop(); if ((cur._x == target._x) && (cur._y == target._y) ) return cur._dist; for (int i = 0; i < 4; i++) { int nx = cur._x + dx[i]; int ny = cur._y + dy[i]; if (CanGo(nx, ny, visited)) { visited[nx][ny] = true; q.push(Cell(nx, ny, cur._dist + 1)); } } } return -1; // 도달 불가 } int solution(vector<vector<int>> maps) { int n = maps.size(); int m = maps[0].size(); board = maps; Cell start(0, 0); Cell exit(n-1,m-1); int toExit = BFS(start, exit); return toExit; }