알고리즘
백준 17129번 윌리암슨수액빨이딱따구리가 정보섬에 올라온 이유 C++
영춘권의달인
2022. 10. 23. 11:16
https://www.acmicpc.net/problem/17129
17129번: 윌리암슨수액빨이딱따구리가 정보섬에 올라온 이유
첫째 줄에 정보섬 2층의 크기 n과 m이 주어진다. (1 ≤ n,m ≤ 3000, 4 ≤ n×m ≤ 9×106) 이후 n행 m열에 걸쳐 0, 1, 2, 3, 4, 5로만 구성된 Ai,j가 주어진다. Ai,j와 Ai,j+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;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
vector<vector<int>> board;
vector<vector<bool>> found;
int n, m;
struct Info {
int row;
int col;
int moveCnt;
};
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));
found = vector<vector<bool>>(n, vector<bool>(m, false));
queue<Info> q;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
for (int j = 0; j < m; j++) {
board[i][j] = str[j] - '0';
if (board[i][j] == 2) {
q.push({ i,j,0 });
found[i][j] = true;
}
}
}
int ans = -1;
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (board[curr.row][curr.col] >= 3 && board[curr.row][curr.col] <= 5) {
ans = curr.moveCnt;
break;
}
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] == 1) continue;
if (found[nextRow][nextCol]) continue;
found[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.moveCnt + 1 });
}
}
if (ans == -1) cout << "NIE";
else cout << "TAK\n" << ans;
}