Inserting nodes whose value in matrix is 1 in the queue .
int k = 1 ; queue < int > q ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { dist [ k ] = 0 ; visit [ k ] = 1 ; q . push ( k ) ; } k ++ ; } }