fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5. #define ul unsigned long long
  6.  
  7. ll mod = 1e9+7;
  8. const int N = 1e3+5;
  9. int MOD = 998244353;
  10. int bit[200000];
  11. int n, m;
  12. //vector<int> adj[N];
  13. int a[N][N];
  14. int d[N][N];
  15. bool visit[N][N];
  16. int sX[] = {0, 0, 1, -1};
  17. int sY[] = {1, -1, 0, 0};
  18.  
  19. void nhap(){
  20. cin >> n >> m;
  21. for(int i= 1 ; i <= n ; i++){
  22. for(int j= 1; j <= m ; j++){
  23. cin >> a[i][j];
  24. }
  25. }
  26. }
  27. void bfs(int sx, int sy) {
  28. queue < pair <int, int> > q;
  29. q.push({sx, sy});
  30. visit[sx][sy] = true;
  31. d[1][1]=1;
  32. while (!q.empty()) {
  33. int x = q.front().first;
  34. int y = q.front().second;
  35. q.pop();
  36.  
  37. for (int i = 0; i < 4; ++i) {
  38. int u = x + sX[i];
  39. int v = y + sY[i];
  40.  
  41. if (u > n || u < 1) continue;
  42. if (v > m || v < 1) continue;
  43.  
  44. if (a[u][v] == 0 && !visit[u][v]) {
  45. visit[u][v] = true;
  46. q.push({u, v});
  47. d[u][v] = d[x][y] + 1;
  48. }
  49. }
  50. }
  51. }
  52. int main() {
  53. //freopen("CSBN.INP", "r", stdin);
  54. //freopen("CSBN.OUT", "w", stdout);
  55. ios_base::sync_with_stdio(0);
  56. cin.tie(0);
  57. cout.tie(0);
  58.  
  59. nhap();
  60. if(a[1][1] == 1){
  61. cout << -1;
  62. return 0;
  63. }
  64. bfs(1,1);
  65.  
  66. cout << d[n][m];
  67.  
  68. }
  69.  
Success #stdin #stdout 0.01s 5516KB
stdin
4 5
01000
01010
00010
11010
stdout
8