Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef pair<int, int> pii;
- typedef tuple<int, int, int, int> tpp;
- pii dir[3] = {pii(1, 0), pii(-1, 0), pii(0, 1)}; // UP DOWN RIGHT
- int row, col;
- bool isInBoard(int r, int c){
- return r >= 1 && r <= row && c >= 1 && c <= col;
- }
- int main(){
- int st;
- scanf("%d%d%d", &row, &col, &st);
- char board[row + 1][col + 2];
- int dist[row + 1][col + 1][3];
- bool visited[row + 1][col + 1][3];
- for(int i = 1; i <= row; ++i){
- for(int j = 1; j <= col; ++j){
- scanf(" %c", &board[i][j]);
- }
- }
- for(int i = 1; i <= row; ++i){
- for(int j = 1; j <= col; ++j){
- for(int d = 0; d < 3; ++d){
- dist[i][j][d] = 1e9;
- visited[i][j][d] = false;
- }
- }
- }
- deque<tpp> dq;
- dist[st][1][2] = 0;
- dq.emplace_back(0, st, 1, 2);
- while(!dq.empty()){
- int ur = get<1>(dq.front());
- int uc = get<2>(dq.front());
- int us = get<3>(dq.front());
- dq.pop_front();
- if(uc == col){
- cout << dist[ur][uc][us];
- return 0;
- }
- if(visited[ur][uc][us]){
- continue;
- }
- visited[ur][uc][us] = true;
- for(int d = 0; d < 3; ++d){
- int vr = ur + dir[d].first;
- int vc = uc + dir[d].second;
- int w = (us == d) ? 0 : 1;
- if(isInBoard(vr, vc) && board[vr][vc] != '#' && !visited[vr][vc][d] && dist[ur][uc][us] + w < dist[vr][vc][d]){
- dist[vr][vc][d] = dist[ur][uc][us] + w;
- if(w == 0){
- dq.emplace_front(dist[vr][vc][d], vr, vc, d);
- } else {
- dq.emplace_back(dist[vr][vc][d], vr, vc, d);
- }
- }
- }
- }
- cout << "-1";
- return 0;
- }
Add Comment
Please, Sign In to add comment