G.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long LL;
  4. const int MAXN = 50 + 10;
  5. int Next[4][2] = {{-1, 0},
  6. {0, 1},
  7. {1, 0},
  8. {0, -1}};
  9. char G[MAXN][MAXN];
  10. int vis[MAXN][MAXN];
  11. int sx, sy;
  12. int ex, ey;
  13. int n, m;
  14. bool BFS() {
  15. memset(vis, 0, sizeof(vis));
  16. queue<pair<int, int> > que;
  17. que.push(make_pair(sx, sy));
  18. vis[sx][sy] = 1;
  19. while (!que.empty()) {
  20. int x = que.front().first;
  21. int y = que.front().second;
  22. que.pop();
  23. if (G[x][y] == 'L')
  24. return true;
  25. for (int i = 0; i < 4; i++) {
  26. int tx = x + Next[i][0];
  27. int ty = y + Next[i][1];
  28. if (tx < 1 || tx > n || ty < 1 || ty > m)
  29. continue;
  30. if (vis[tx][ty] == 1 || G[tx][ty] == 'x')
  31. continue;
  32. que.push(make_pair(tx, ty));
  33. vis[tx][ty] = 1;
  34. }
  35. }
  36. return false;
  37. }
  38. int main() {
  39. while (cin >> n >> m) {
  40. for (int i = 1; i <= n; i++) {
  41. for (int j = 1; j <= m; j++) {
  42. cin >> G[i][j];
  43. if (G[i][j] == 'S')
  44. sx = i, sy = j;
  45. if (G[i][j] == 'L')
  46. ex = i, ey = j;
  47. }
  48. }
  49. if (BFS())
  50. cout << "I saved him." << endl;
  51. else
  52. cout << "Sorry, I can't save him." << endl;
  53. }
  54. return 0;
  55. }