Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <map>
- using namespace std;
- #define N 101
- int labyrinth[N][N];
- int n, m;
- struct Ver {
- int x, y;
- Ver(int a, int b) {
- x = a;
- y = b;
- }
- };
- queue<Ver>que;
- map<Ver, int> top;
- bool operator< (const Ver& a, const Ver& b) {
- return b.x > a.x;
- }
- int right(int x,int y) {
- int i = y;
- while (labyrinth[x][i + 1] != 1) {
- i++;
- }
- return i ;
- }
- int left(int x,int y) {
- int i = y;
- while (labyrinth[x][i - 1] != 1) {
- i--;
- }
- return i ;
- }
- int up(int x, int y) {
- int i = x;
- while (labyrinth[i-1][y] != 1) {
- i--;
- }
- return i;
- }
- int down(int x, int y) {
- int i = x;
- while (labyrinth[i+1][y] != 1) {
- i++;
- }
- return i;
- }
- void bfs(int x, int y) {
- map<Ver, int>::iterator it;
- top.insert(pair<Ver, int> (Ver(x,y), 1));
- que.push(Ver(x, y));
- while (que.size() != 0) {
- int a = que.front().x;
- int b = que.front().y;
- que.pop();
- it = top.find(Ver(a, b));
- if (labyrinth[a][b] == 2) {
- cout << it->second;
- return;
- }
- int bend = it->second + 1;
- int r = right(a, b);
- if (top.count(Ver(a, r)) != 1) {
- que.push(Ver(a, r));
- top.insert(pair<Ver, int>(Ver(a, r), bend));
- }
- int l = left(a, b);
- if (top.count(Ver(a, l)) != 1) {
- que.push(Ver(a, l));
- top.insert(pair<Ver, int>(Ver(a, l), bend));
- }
- int u = up(a, b);
- if (top.count(Ver(u, b)) != 1) {
- que.push(Ver(u, b));
- top.insert(pair<Ver, int>(Ver(u, b), bend));
- }
- int d = down(a, b);
- if (top.count(Ver(d, b)) != 1) {
- que.push(Ver(d, b));
- top.insert(pair<Ver, int>(Ver(d, b), bend));
- }
- }
- }
- int main() {
- cin >> n >> m;
- for (int i = 1; i <= n ; i++) {
- for (int j = 1; j <= m; j++) {
- cin >> labyrinth[i][j];
- }
- }
- for (int i = 0; i <= m + 1; i++) {
- labyrinth[0][i] = 1;
- labyrinth[n + 1][i] = 1;
- }
- for (int i = 0; i <= n + 1; i++) {
- labyrinth[i][m + 1] = 1;
- labyrinth[i][0] = 1;
- }
- bfs(1, 1);
- return 0;
- }
Add Comment
Please, Sign In to add comment