알고리즘
백준 14940번 쉬운 최단거리 C++
영춘권의달인
2023. 1. 17. 12:27
https://www.acmicpc.net/problem/14940
14940번: 쉬운 최단거리
지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000) 다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이
www.acmicpc.net
bfs
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
struct Info {
int row;
int col;
int moveCnt;
};
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
int n, m;
vector<vector<int>> board;
vector<vector<int>> resultBoard;
vector<vector<bool>> found;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
board = vector<vector<int>>(n, vector<int>(m));
resultBoard = vector<vector<int>>(n, vector<int>(m, -1));
found = vector<vector<bool>>(n, vector<bool>(m, false));
pair<int, int> startPos;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> board[i][j];
if (board[i][j] == 0) resultBoard[i][j] = 0;
if (board[i][j] == 2) startPos = { i,j };
}
}
queue<Info> q;
q.push({ startPos.first,startPos.second,0 });
found[startPos.first][startPos.second] = true;
while (!q.empty()) {
auto curr = q.front();
q.pop();
resultBoard[curr.row][curr.col] = curr.moveCnt;
for (int i = 0; i < 4; i++) {
int nextRow = curr.row + dRow[i];
int nextCol = curr.col + dCol[i];
if (nextRow < 0 || nextRow >= n) continue;
if (nextCol < 0 || nextCol >= m) continue;
if (board[nextRow][nextCol] == 0) continue;
if (found[nextRow][nextCol]) continue;
found[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.moveCnt + 1 });
}
}
for (auto a : resultBoard) {
for (auto b : a) {
cout << b << " ";
}
cout << "\n";
}
}