Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <vector>
- using namespace std;
- int main() {
- int n, m;
- cin >> n >> m;
- char mat[n][m];
- int si, sj, ei, ej;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- if(mat[i][j] == 'P') {
- si = i;
- sj = j;
- }
- if(mat[i][j] == 'K') {
- ei = i;
- ej = j;
- }
- }
- }
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0, -1, 1};
- int di2[] = {-2, 2, 0, 0};
- int dj2[] = {0, 0, -2, 2};
- int di3[] = {-3, 3, 0, 0};
- int dj3[] = {0, 0, -3, 3};
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- vector<vector<bool>> visited2(n, vector<bool>(m, false));
- vector<vector<bool>> visited3(n, vector<bool>(m, false));
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0);
- q.push(1); // dali ke odime 1, 2 ili 3 cekori
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- int dist = q.front();
- q.pop();
- int direction = q.front();
- q.pop();
- if(ci == ei and cj == ej) {
- cout << dist << endl;
- return 0;
- }
- if(direction == 1) {
- for(int i = 0; i < 4; i++) {
- int ti = ci + di[i];
- int tj = cj + dj[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and !visited[ti][tj]) {
- q.push(ti);
- q.push(tj);
- q.push(dist + 1);
- q.push(2);
- visited[ti][tj] = true;
- }
- }
- }
- else if(direction == 2) {
- for(int i = 0; i < 4; i++) {
- int ti = ci + di[i];
- int tj = cj + dj[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#') {
- ti = ci + di2[i];
- tj = cj + dj2[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and !visited2[ti][tj]) {
- q.push(ti);
- q.push(tj);
- q.push(dist + 1);
- q.push(3);
- visited2[ti][tj] = true;
- }
- }
- }
- }
- else if(direction == 3) {
- for(int i = 0; i < 4; i++) {
- int ti = ci + di[i];
- int tj = cj + dj[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#') {
- ti = ci + di2[i];
- tj = cj + dj2[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#') {
- ti = ci + di3[i];
- tj = cj + dj3[i];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and !visited3[ti][tj]) {
- q.push(ti);
- q.push(tj);
- q.push(dist + 1);
- q.push(1);
- visited3[ti][tj] = true;
- }
- }
- }
- }
- }
- }
- return 0;
- }
- /*
- P.#K#
- .##.#
- .....
- .....
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement