#include<iostream>#include<vector>usingnamespace std;int count =0;int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};voiddfs(vector<vector<int>>&graph,int row,int col){
graph[row][col]=0;
count++;for(int i =0; i <4; i++){int nextRow = row + dir[i][0];int nextCol = col + dir[i][1];if(nextRow <0|| nextRow >= graph.size()|| nextCol <0|| nextCol >= graph[0].size()){continue;}if(graph[nextRow][nextCol]==1){dfs(graph, nextRow, nextCol);}}}intmain(){int N, M;
cin >> N >> M;
vector<vector<int>>graph(N,vector<int>(M));for(int i =0; i < N; i++){for(int j =0; j < M; j++){
cin >> graph[i][j];}}for(int i =0; i < N; i++){if(graph[i][0]==1){dfs(graph, i,0);}if(graph[i][M -1]==1){dfs(graph, i, M -1);}}for(int j =0; j < M; j++){if(graph[0][j]==1){dfs(graph,0, j);}if(graph[N -1][j]==1){dfs(graph, N -1, j);}}
count =0;for(int i =1; i < N -1; i++){for(int j =1; j < M -1; j++){if(graph[i][j]==1){dfs(graph, i, j);}}}
cout << count;return0;}
#include<iostream>#include<vector>#include<queue>usingnamespace std;int count =0;int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};voidbfs(vector<vector<int>>&graph,int row,int col){
count++;
graph[row][col]=0;
queue<pair<int,int>> que;
que.push({row, col});while(!que.empty()){
pair<int,int> pa = que.front();
que.pop();for(int i =0; i <4; i++){int nextRow = pa.first + dir[i][0];int nextCol = pa.second + dir[i][1];if(nextRow <0|| nextRow >= graph.size()|| nextCol <0|| nextCol >= graph[0].size()){continue;}if(graph[nextRow][nextCol]==1){
count++;
graph[nextRow][nextCol]=0;
que.push({nextRow, nextCol});}}}}intmain(){int N, M;
cin >> N >> M;
vector<vector<int>>graph(N,vector<int>(M));for(int i =0; i < N; i++){for(int j =0; j < M; j++){
cin >> graph[i][j];}}for(int i =0; i < N; i++){if(graph[i][0]==1){bfs(graph, i,0);}if(graph[i][M -1]==1){bfs(graph, i, M -1);}}for(int j =0; j < M; j++){if(graph[0][j]==1){bfs(graph,0, j);}if(graph[N -1][j]==1){bfs(graph, N -1, j);}}
count =0;for(int i =1; i < N -1; i++){for(int j =1; j < M -1; j++){if(graph[i][j]==1){bfs(graph, i, j);}}}
cout << count;return0;}