Problem of 8 Neighbours of an element in a 2 | Java implementation of the approach ; Dimension of Array ; Count of 1 s ; Counting all neighbouring 1 s ; Comparing the number of neighbouring 1 s with given ranges ; Copying changes to the main matrix ; Driver code ; Function call to calculate the resultant matrix after ' K ' iterations . ; Printing Result
public class GFG { final static int N = 4 ; static void predictMatrix ( int arr [ ] [ ] , int range1a , int range1b , int range0a , int range0b , int K , int b [ ] [ ] ) { int c = 0 ; while ( K != 0 ) { K -- ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { c = 0 ; if ( i > 0 && arr [ i - 1 ] [ j ] == 1 ) c ++ ; if ( j > 0 && arr [ i ] [ j - 1 ] == 1 ) c ++ ; if ( i > 0 && j > 0 && arr [ i - 1 ] [ j - 1 ] == 1 ) c ++ ; if ( i < N - 1 && arr [ i + 1 ] [ j ] == 1 ) c ++ ; if ( j < N - 1 && arr [ i ] [ j + 1 ] == 1 ) c ++ ; if ( i < N - 1 && j < N - 1 && arr [ i + 1 ] [ j + 1 ] == 1 ) c ++ ; if ( i < N - 1 && j > 0 && arr [ i + 1 ] [ j - 1 ] == 1 ) c ++ ; if ( i > 0 && j < N - 1 && arr [ i - 1 ] [ j + 1 ] == 1 ) c ++ ; if ( arr [ i ] [ j ] == 1 ) { if ( c >= range1a && c <= range1b ) b [ i ] [ j ] = 1 ; else b [ i ] [ j ] = 0 ; } if ( arr [ i ] [ j ] == 0 ) { if ( c >= range0a && c <= range0b ) b [ i ] [ j ] = 1 ; else b [ i ] [ j ] = 0 ; } } } for ( int k = 0 ; k < N ; k ++ ) for ( int m = 0 ; m < N ; m ++ ) arr [ k ] [ m ] = b [ k ] [ m ] ; } } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 0 , 0 , 0 , 0 } , { 0 , 1 , 1 , 0 } , { 0 , 0 , 1 , 0 } , { 0 , 1 , 0 , 1 } } ; int range1a = 2 , range1b = 2 ; int range0a = 2 , range0b = 3 ; int K = 3 ; int b [ ] [ ] = new int [ N ] [ N ] ; predictMatrix ( arr , range1a , range1b , range0a , range0b , K , b ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . println ( ) ; for ( int j = 0 ; j < N ; j ++ ) System . out . print ( b [ i ] [ j ] + " ▁ " ) ; } } }