Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <cstring>
- #include <queue>
- using namespace std;
- const int maxn = 305;
- char mat[maxn][maxn];
- bool visited[maxn][maxn][4];
- int main() {
- ios_base::sync_with_stdio(false);
- int n, m;
- cin >> 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;
- }
- }
- }
- memset(visited, false, sizeof visited);
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(1);
- q.push(0);
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0, -1, 1};
- while(!q.empty()) {
- int ci = q.front(); q.pop();
- int cj = q.front(); q.pop();
- int step = q.front(); q.pop();
- int shortest_dist = q.front(); q.pop();
- if(ci == ei and cj == ej) {
- cout << shortest_dist << endl;
- return 0;
- }
- for(int i = 0; i < 4; i++) {
- bool ok = true;
- for(int j = 1; j <= step; j++) {
- int ti = di[i] * j + ci;
- int tj = dj[i] * j + cj;
- if(ti < 0 or ti >= n or tj < 0 or tj >= m or mat[ti][tj] == '#') {
- ok = false;
- break;
- }
- }
- if(ok) {
- int new_step = step + 1;
- if(new_step > 3) {
- new_step = 1;
- }
- int ti = di[i] * step + ci;
- int tj = dj[i] * step + cj;
- if(!visited[ti][tj][new_step]) {
- q.push(ti);
- q.push(tj);
- q.push(new_step);
- q.push(shortest_dist + 1);
- visited[ti][tj][new_step] = true;
- }
- }
- }
- }
- return 0;
- }
- /*
- P......
- #.##K..
- .#.#..#
- ##..##.
- di[] = {-1, 1, 0, 0}
- dj[] = {0, 0, -1, 1}
- cekor = 3
- **/
Advertisement
Add Comment
Please, Sign In to add comment