fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. int main()
  7. {
  8. int m, n;
  9.  
  10. cout << "Give M and N - ";
  11. cin >> m >> n;
  12.  
  13. int a[m][n];
  14.  
  15. for ( int i = 0; i < m; i++ )
  16. {
  17. for ( int j = 0; j < n; j++ )
  18. {
  19. cin >> a[i][j];
  20. }
  21. }
  22.  
  23.  
  24. int smax = -1, suma = -1, x = -1, y = -1;
  25.  
  26. for ( int i = 0; i < m; i++ )
  27. {
  28. for ( int j = 0; j < n; j++ )
  29. {
  30. suma = 0;
  31. if ( i + 1 >= m || j + 1 >= n )
  32. {
  33. // No 2x2 matrix exists for this i and j.
  34. continue;
  35. }
  36.  
  37. for ( int k = i; k < i + 2; k++ )
  38. {
  39. for ( int l = j; l < j + 2; l++ )
  40. {
  41. suma = suma + a[k][l];
  42. }
  43. }
  44.  
  45. if ( suma > smax )
  46. {
  47. smax = suma;
  48. x = i, y = j;
  49. }
  50. }
  51. }
  52.  
  53. cout << endl << x << " " << y << " " << smax << endl;
  54.  
  55. if ( x == -1 || y == -1 )
  56. {
  57. // No 2x2 matrix found!
  58. cout << "Invalid input!" << endl;
  59. return 0;
  60. }
  61.  
  62. for ( int i = x; i < x + 2; i++ )
  63. {
  64. for ( int j = y; j < y + 2; j++ )
  65. {
  66. cout << a[i][j] << " ";
  67. }
  68. cout << endl;
  69. }
  70.  
  71. }
Success #stdin #stdout 0s 3416KB
stdin
4 4

4 2 7 11
3 8 19 1
11 12 7 5
19 14 4 7
stdout
Give M and N - 
2 0 56
11 12 
19 14