we were discussing a problem of finding the largest submatrix of 1 in a boolean matrix.
we presented several techniques to solve this including histogram method, iterative method and depth first approach. The depth first approach can find the number as well as sise of islands of 1s. This method explores all eight neighbors of a point. Therefore it visits all points in an island before going to the next island. This helps in knowing the size of the island before going to the others which also helps us deternine the largest island.
void DFS(int[,] A, int ROW, int COL, int row, int col, ref int[,] visited, ref int size)
{
var rd = { -1,-1,-1,0,0,1,1, 1};
var cd = { -1,0,1,-1,0,1,-1,0,1 };
visited[row,col] = true;
for (int k = 0; k < 8; k++)
if (isSafe(A, ROW, COL, row + rd[k], col +cd[k])){
size++;
DFS(A, ROW, COL, row+rd[k], col+cd[k], ref visited, ref size);
}
}
bool isSafe( int[,] A, int ROW, int COL, int row, int col, ref int[,] visited)
{
if ( row >= 0 && row < ROW &&
col >= 0 && col < COL &&
A[row, col] == 1 && !visited[row,col])
return true;
return false;
}
int countIslands(int[,] A, int ROW, int COL)
{
var visited = new bool[ROW, COL] { False }
int count = 0;
int maxsize = 0;
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
if ( A[i,j] == 1 && !visited[i, j])
{
int size = 0;
count++;
DFS(A, ROW, COL, i, j, ref visited, ref size);
if (size > maxSize)
maxSize = size;
}
}
we presented several techniques to solve this including histogram method, iterative method and depth first approach. The depth first approach can find the number as well as sise of islands of 1s. This method explores all eight neighbors of a point. Therefore it visits all points in an island before going to the next island. This helps in knowing the size of the island before going to the others which also helps us deternine the largest island.
void DFS(int[,] A, int ROW, int COL, int row, int col, ref int[,] visited, ref int size)
{
var rd = { -1,-1,-1,0,0,1,1, 1};
var cd = { -1,0,1,-1,0,1,-1,0,1 };
visited[row,col] = true;
for (int k = 0; k < 8; k++)
if (isSafe(A, ROW, COL, row + rd[k], col +cd[k])){
size++;
DFS(A, ROW, COL, row+rd[k], col+cd[k], ref visited, ref size);
}
}
bool isSafe( int[,] A, int ROW, int COL, int row, int col, ref int[,] visited)
{
if ( row >= 0 && row < ROW &&
col >= 0 && col < COL &&
A[row, col] == 1 && !visited[row,col])
return true;
return false;
}
int countIslands(int[,] A, int ROW, int COL)
{
var visited = new bool[ROW, COL] { False }
int count = 0;
int maxsize = 0;
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
if ( A[i,j] == 1 && !visited[i, j])
{
int size = 0;
count++;
DFS(A, ROW, COL, i, j, ref visited, ref size);
if (size > maxSize)
maxSize = size;
}
}
No comments:
Post a Comment