Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <queue>
- #include <cstring>
- using namespace std;
- bool visited[22][22][1 << 8];
- int main()
- {
- memset(visited, false, sizeof visited);
- 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;
- }
- }
- }
- queue<int> Q;
- Q.push(si);
- Q.push(sj);
- Q.push(0); // ova ni e maska za da znaeme koi klucevi gi imame momentalno zemeno
- Q.push(0); // kolku cekori sme napravile do sega
- visited[si][sj][0] = true;
- 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 keys = Q.front();
- Q.pop();
- int cekor = Q.front();
- Q.pop();
- if(ci == ei and cj == ej) {
- cout << cekor << endl;
- return 0;
- }
- 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) {
- if(mat[ti][tj] == '#') {
- continue;
- }
- if(mat[ti][tj] == '.' or mat[ti][tj] == 'K') {
- if(!visited[ti][tj][keys]) {
- Q.push(ti);
- Q.push(tj);
- Q.push(keys);
- Q.push(cekor + 1);
- visited[ti][tj][keys] = true;
- }
- }
- if(mat[ti][tj] >= 'a' and mat[ti][tj] <= 'h') { // sme stapnale na kluc
- int key_index = (mat[ti][tj] - 'a');
- int new_keys = keys | (1 << key_index);
- if(!visited[ti][tj][new_keys]) {
- Q.push(ti);
- Q.push(tj);
- Q.push(new_keys);
- Q.push(cekor + 1);
- visited[ti][tj][new_keys] = true;
- }
- }
- if(mat[ti][tj] >= 'A' and mat[ti][tj] <= 'H') {
- int key_index = (mat[ti][tj] - 'A');
- if(keys & (1 << key_index)) {
- if(!visited[ti][tj][keys]) {
- Q.push(ti);
- Q.push(tj);
- Q.push(keys);
- Q.push(cekor + 1);
- visited[ti][tj][keys] = true;
- }
- }
- }
- }
- }
- }
- cout << -1 << endl;
- return 0;
- }
- /*
- 5 5
- P..#a
- A....
- .####
- K....
- #####
- 10 10
- P.....d..f
- ####F#D###
- ..........
- ......h..b
- .#####H###
- .#....a...
- .#.###A###
- .#.#...c..
- .#.#.####C
- .B.#.#...K
- 3 3
- P.A
- ##a
- K..
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement