Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- #include <cmath>
- #include <math.h>
- #include <vector>
- #include <queue>
- using namespace std;
- char mat[105][105];
- bool visited[105][105][1 << 8];
- int main()
- {
- int n, m;
- cin >> n >> m;
- int si, sj;
- int 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') { // pocetok
- si = i;
- sj = j;
- }
- if(mat[i][j] == 'K') {
- ei = i;
- ej = j;
- }
- }
- }
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- for(int mask = 0; mask < (1 << 8); mask++) {
- visited[i][j][mask] = false;
- }
- }
- }
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0); // koi klucevi do sega sme gi zemale
- q.push(0); // kolku cekori do tuka sme pominale
- 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 bitmask = q.front();
- q.pop();
- int cekor = q.front();
- q.pop();
- if(mat[ci][cj] == 'K') {
- 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 and mat[ti][tj] != '#') {
- if(mat[ti][tj] >= 'a' and mat[ti][tj] <= 'h') {
- int bukva = mat[ti][tj] - 'a';
- int zemeno = bitmask | (1 << bukva);
- if(!visited[ti][tj][zemeno]) {
- visited[ti][tj][zemeno] = true;
- q.push(ti);
- q.push(tj);
- q.push(zemeno);
- q.push(cekor + 1);
- }
- }
- else if(mat[ti][tj] >= 'A' and mat[ti][tj] <= 'H') {
- int bukva = mat[ti][tj] - 'A';
- if(bitmask & (1 << bukva)) {
- if(!visited[ti][tj][bitmask]) {
- q.push(ti);
- q.push(tj);
- q.push(bitmask);
- q.push(cekor + 1);
- visited[ti][tj][bitmask] = true;
- }
- }
- }
- else {
- if(!visited[ti][tj][bitmask]) {
- visited[ti][tj][bitmask] = true;
- q.push(ti);
- q.push(tj);
- q.push(bitmask);
- q.push(cekor + 1);
- }
- }
- }
- }
- }
- cout << "Ne moze da se stigne do kraj" << endl;
- return 0;
- }
- /*
- P..A
- ..#K
- ...#
- a...
- 10 10
- P.....d..f
- ####F#D###
- ..........
- ......h..b
- .#####H###
- .#....a...
- .#.###A###
- .#.#...c..
- .#.#.####C
- .B.#.#...K
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement