E - Bishop 2
E - Bishop 2
https://atcoder.jp/contests/abc246/tasks/abc246_e
思想
BFS遍历。
Code
https://atcoder.jp/contests/abc246/submissions/38443616
bool pts[1505][1505]; // if blocked bool vis[1505][1505]; // visited bool add[1505][1505]; // added int mvs[1505][1505]; // num of moves int n; int ax, ay; int bx, by; typedef struct node{ int x; int y; } NODE; int main() { cin >> n; cin >> ax >> ay; cin >> bx >> by; for(int i=0; i<n; i++){ string si; cin >> si; for(int j=0; j<n; j++){ char one = si[j]; if (one == '.'){ pts[i+1][j+1] = true; } else if(one == '#'){ pts[i+1][j+1] = false; } mvs[i+1][j+1] = -1; vis[i+1][j+1] = false; add[i+1][j+1] = false; } } NODE one; one.x = ax; one.y = ay; queue<NODE> qq; qq.push(one); mvs[ax][ay] = 0; add[ax][ay] = true; while(!qq.empty()){ NODE cur = qq.front(); qq.pop(); int x = cur.x; int y = cur.y; vis[x][y] = true; // cout << "visited. x=" << x << "y=" << y << endl; if (x == bx && y == by){ cout << mvs[x][y] << endl; return 0; } int ix, iy; ix = x; iy = y; while(ix+1>=1 && ix+1<=n && iy+1>=1 && iy+1<=n && pts[ix+1][iy+1]){ ix++; iy++; if (vis[ix][iy]){ continue; } if (add[ix][iy]){ continue; } NODE one; one.x = ix; one.y = iy; qq.push(one); add[ix][iy] = true; // cout << "1-added. x=" << ix << "y=" << iy << endl; mvs[ix][iy] = mvs[x][y] + 1; } ix = x; iy = y; while(ix+1>=1 && ix+1<=n && iy-1>=1 && iy-1<=n && pts[ix+1][iy-1]){ ix++; iy--; if (vis[ix][iy]){ continue; } if (add[ix][iy]){ continue; } NODE one; one.x = ix; one.y = iy; qq.push(one); add[ix][iy] = true; // cout << "2-added. x=" << ix << "y=" << iy << endl; mvs[ix][iy] = mvs[x][y] + 1; } ix = x; iy = y; while(ix-1>=1 && ix-1<=n && iy+1>=1 && iy+1<=n && pts[ix-1][iy+1]){ ix--; iy++; if (vis[ix][iy]){ continue; } if (add[ix][iy]){ continue; } NODE one; one.x = ix; one.y = iy; qq.push(one); add[ix][iy] = true; // cout << "3-added. x=" << ix << "y=" << iy << endl; mvs[ix][iy] = mvs[x][y] + 1; } ix = x; iy = y; while(ix-1>=1 && ix-1<=n && iy-1>=1 && iy-1<=n && pts[ix-1][iy-1]){ ix--; iy--; if (vis[ix][iy]){ continue; } if (add[ix][iy]){ continue; } NODE one; one.x = ix; one.y = iy; qq.push(one); add[ix][iy] = true; // cout << "4-added. x=" << ix << "y=" << iy << endl; mvs[ix][iy] = mvs[x][y] + 1; } } cout << -1 << endl; return 0; }
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。