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. bool visit[N][N];
  15. int sX[] = {0, 0, 1, -1};
  16. int sY[] = {1, -1, 0, 0};
  17. int dem = 1;
  18. void nhap(){
  19. cin >> n >> m;
  20. for(int i= 1 ; i <= n ; i++){
  21. for(int j= 1; j <= m ; j++){
  22. cin >> a[i][j];
  23. }
  24. }
  25. }
  26. void bfs(int sx, int sy) {
  27. queue < pair <int, int> > q;
  28. q.push({sx, sy});
  29. visit[sx][sy] = true;
  30. while (!q.empty()) {
  31. int x = q.front().first;
  32. int y = q.front().second;
  33. q.pop();
  34.  
  35. for (int i = 0; i < 4; ++i) {
  36. int u = x + sX[i];
  37. int v = y + sY[i];
  38.  
  39. if (u > n || u < 1) continue;
  40. if (v > m || v < 1) continue;
  41.  
  42. if (a[u][v] == 0 && !visit[u][v]) {
  43. visit[u][v] = true;
  44. q.push({u, v});
  45. dem++;
  46. }
  47. }
  48. }
  49. }
  50. int main() {
  51. //freopen("CSBN.INP", "r", stdin);
  52. //freopen("CSBN.OUT", "w", stdout);
  53. ios_base::sync_with_stdio(0);
  54. cin.tie(0);
  55. cout.tie(0);
  56.  
  57. nhap();
  58. if(a[1][1] == 1){
  59. cout << -1;
  60. }
  61. else{
  62. bfs(1,1);
  63.  
  64. cout << dem;
  65. }
  66. }
  67.  
Success #stdin #stdout 0.01s 5316KB
stdin
4 5
01000
01010
00010
11010
stdout
17