In: Computer Science
Declare two 2d arrays n0[MAX_ROW][MAX_COL], n1
[MAX_ROW][MAX_COL].
Then, loop through the 2d array and save the results in n0 and
n1:
for (i=0; i<MAX_ROW; i++)
for (j=0; j<MAX_COL;j++){
//calculate number of
zeros around entry a[i][j]
n0[i][j] =
//calculate number of
ones around entry a[i][j]
n1[i][j] =
}
Set the MAX_ROW and MAX_COL to a small number and display all three 2d arrays on the screen to verify that the calculations are correct. You may still use command-line inputs as in the example program to set the actual size of the array (must be less than or equal to MAX_ROW, MAX_COL.
import java .io.*;
class GFG
{
static int R = 4;
static int C = 4;
static int getTotalCoverageOfMatrix(int [][]mat)
{
int res = 0;
for (int i = 0; i < R; i++)
{
boolean isOne = false;
for (int j = 0; j < C; j++)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
isOne = false;
for (int j = C - 1; j >= 0; j--)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
for (int j = 0; j < C; j++)
{
boolean isOne = false;
for (int i = 0; i < R; i++)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
isOne = false;
for (int i = R - 1; i >= 0; i--)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
return res;
}
static public void main (String[] args)
{
int [][]mat = {{0, 0, 0, 0},
{1, 0, 0, 1},
{0, 1, 1, 0},
{0, 1, 0, 0}};
System.out.println(
getTotalCoverageOfMatrix(mat));
}
}