ann8497

UnitAreaOfLargestOne Samsung

Jun 18th, 2019
1,326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int a[500][500];
  4. bool visited[500][500];
  5. int len[500][500];
  6. int rows, cols;
  7. int X[8] = {-1,-1,-1,0,1,1,1,0};
  8. int Y[8] = {-1,0,1,1,1,0,-1,-1};
  9.  
  10. struct s{
  11.     int r, c;
  12. };
  13.  
  14. bool valid(int r, int c) {
  15.     if(r<rows && c<cols && r>=0 && c>=0)return true;
  16.     return false;
  17. }
  18.  
  19. int calculate(){
  20.     int ans = 0;
  21.     for(int i =0; i<rows; i++)for(int j =0; j<cols; j++)ans += len[i][j];
  22.     return ans;
  23. }
  24.  
  25. int solve(int r, int c){
  26.     queue<s>q;
  27.     s temp; temp.r = r; temp.c = c;
  28.     q.push(temp);
  29.     visited[r][c] = true; len[r][c] = 1;
  30.    
  31.     while(!q.empty()){
  32.         s topp = q.front();
  33.         int R = topp.r; int C = topp.c;
  34.         q.pop();
  35.        
  36.         for(int i = 0; i<8; i++){
  37.              int x = R + X[i]; int y = C + Y[i];
  38.              if(valid(x,y))
  39.              if(a[x][y] == 1 && visited[x][y] == false){
  40.                  s temp1; temp1.r = x; temp1.c = y;
  41.                  q.push(temp1);
  42.                  len[x][y] = 1;
  43.                  visited[x][y] = true;
  44.              }
  45.         }
  46.     }
  47.     return calculate();
  48. }
  49.  
  50.  
  51. int main() {
  52.     int t; cin>>t;
  53.     while(t--){
  54.     int ans = 0;
  55.     memset(visited, 0 , sizeof(visited));
  56.     cin>>rows>>cols;
  57.  
  58.     for(int i =0; i<rows; i++)for(int j =0; j<cols; j++) cin>>a[i][j];
  59.      
  60.         for(int i =0; i<rows; i++){
  61.             for(int j =0; j<cols; j++){
  62.                 if(a[i][j] == 1 && visited[i][j] == false){
  63.                     memset(len, 0, sizeof(len));
  64.                     ans = max( ans, solve(i,j) );
  65.                 }
  66.             }
  67.         }
  68.        
  69.         cout<<ans<<endl;
  70.     }
  71.    
  72.     return 0;
  73. }
Add Comment
Please, Sign In to add comment