- 2
Try it out in c/java
Consider a 2D matrix of numbers from 0 to 9 with variable width and height. Find the square submatrix with the highest sum of boundary elements. Input : Input width and height of matrix: 6 8 Input Matrix with numbers from 0 to 9: 2 0 6 1 2 5 1 0 5 0 1 3 3 0 1 2 4 1 0 1 3 1 1 9 4 1 0 8 5 2 0 1 0 1 2 3 6 5 3 1 0 2 0 0 1 6 0 4 Input maximum width of square submatrix (for square submatrix height and width are same) : 3 Output : As sum of highlighted submatrix is maximum (calcute sum of boundary elements only 2,4,1,9,2,5,8,1), 2 0 6 1 2 5 1 0 5 0 1 3 3 0 1 2 4 1 0 1 3 1 1 9 4 1 0 8 5 2 0 1 0 1 2 3 6 5 3 1 0 2 0 0 1 6 0 4 Output should be : 2 4 1 1 1 9 8 5 2
1 Antwort
0
import java.util.Scanner;
public class Main
{
void avgsubMatrix(int arr[][])
{
int row = arr.length-2;
int col = arr[0].length-2;
int sum,maxSum=0,subRow=0,subCol=0;
for(int i=0;i<row;i++)
{
sum = 0;
for(int j=0;j<col;j++)
{
sum = arr[i][j] + arr[i][j+1] + arr[i][j+2]+ arr[i+1][j] + arr[i+1][j+1] + arr[i+1][j+2]+arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2];
if(maxSum < sum)
{
maxSum = sum;
subRow = i;
subCol = j;
}
}
}
for(int i=subRow;i<subRow+3;i++)
{
for(int j=subCol;j<subCol+3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args)
{
Main s=new Main();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Row Size of Matrix ");
int row = sc.nextInt();
System.out.print("Enter Column size of matrix:");
int col = sc.nextInt();
int Matrix[][] = new int[row][col];
System.out.println("Enter Matrix element between 0 to 9");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
Matrix[i][j] = sc.nextInt();
}
}
s.avgsubMatrix(Matrix);
}
}