Let a matrix of size m X n contains elements either 0 or 1. Write a code to replace an element 0 with 1, if all its surrounding elements are 1.
#include<stdio.h>
#define M 6
#define N 6
void floodFillUtil(char matrix[][N], int x, int y, char prev, char new)
{
if (x < 0 || x >= M || y < 0 || y >= N)
return;
if (matrix[x][y] != prev)
return;
matrix[x][y] = new;
floodFillUtil(matrix, x+1, y, prev, new);
floodFillUtil(matrix, x-1, y, prev, new);
floodFillUtil(matrix, x, y+1, prev, new);
floodFillUtil(matrix, x, y-1, prev, new);
}
int replaceSurrounded(char matrix[][N])
{
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
if (matrix[i][j] == 'O')
matrix[i][j] = '-';
for (int i=0; i<M; i++)
if (matrix[i][0] == '-')
floodFillUtil(matrix, i, 0, '-', 'O');
for (int i=0; i<M; i++)
if (matrix[i][N-1] == '-')
floodFillUtil(matrix, i, N-1, '-', 'O');
for (int i=0; i<N; i++)
if (matrix[0][i] == '-')
floodFillUtil(matrix, 0, i, '-', 'O');
for (int i=0; i<N; i++)
if (matrix[M-1][i] == '-')
floodFillUtil(matrix, M-1, i, '-', 'O');
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
if (matrix[i][j] == '-')
matrix[i][j] = '1';
}
int main()
{
char matrix[][N] = {{'1', 'O', '1', 'O', '1', '1'},
{'1', 'O', '1', '1', 'O', '1'},
{'1', '1', '1', 'O', '1', '1'},
{'O', '1', '1', '1', '1', '1'},
{'1', '1', '1', 'O', '1', 'O'},
{'O', 'O', '1', 'O', 'O', 'O'},
};
replaceSurrounded(matrix);
int mat[6][6] = {{1, 0, 1, 0, 1, 1},
{1, 0, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1},
{1, 1, 1, 0, 1, 0},
{0, 0, 1, 0, 0, 0},
};
int row, column=0;
for (row=0; row<6; row++)
{
for(column=0; column<6; column++)
{printf("%d ", mat[row][column]);}
printf("\n");
}
getchar();
}
Comments
Leave a comment