【发布时间】:2021-05-17 16:38:53
【问题描述】:
考虑一个矩阵,其中每个单元格包含 0 或 1。任何包含 1 的单元格都称为填充单元格。如果两个单元在水平、垂直或对角线上彼此相邻,则称它们是连接的。在下面的网格中,所有标记为 X 的单元格都连接到标记为 Y 的单元格。
XXX
XYX
XXX
如果一个或多个填充的单元格也连接起来,它们形成一个区域。请注意,区域中的每个单元都与该区域中的零个或多个单元相连,但不一定直接与该区域中的所有其他单元相连。
给定一个 nXm 矩阵,找出并打印矩阵中最大区域的单元格数。请注意,矩阵中可能有多个区域。
例如:
Sample Input:
5 4
0 0 1 1
0 0 1 0
0 1 1 0
0 1 0 0
1 1 0 0
OUTPUT: 8
我试图解决这个问题,下面是我尝试过的。问题是我在矩阵中的 dfs 搜索从未完成。它在一些步骤后终止。我不知道我哪里错了?
#include<bits/stdc++.h>
using namespace std;
bool isValid (int row, int column, int n, int m, bool** visited){
if(row<0 || row>n-1 || column<0 || column>m-1){
return false;
}
if(visited[row][column]==true){
return false;
}
return true;
}
int countConnectedCells(int** arr, int n, int m, bool** visited, int row, int column){
visited[row][column]=1;
int current_maximum=0;
if(arr[row][column]==1){
current_maximum=1;
//Down
if(isValid(row+1,column, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row+1, column);
}
//Right
if(isValid(row,column+1, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row, column+1);
}
//Left
if(isValid(row,column-1, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row, column-1);
}
//Upward
if(isValid(row-1,column, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row-1, column);
}
//UpwardLeft
if(isValid(row-1,column-1, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row-1, column-1);
}
//UpwardRight
if(isValid(row-1,column+1, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row-1, column+1);
}
//DownwardRight
if(isValid(row+1,column+1, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row+1, column+1);
}
//DownLeft
if(isValid(row+1,column-1, n, m, visited)){
current_maximum+=countConnectedCells(arr, n, m, visited, row+1, column-1);
}
}
return current_maximum;
}
int main(){
int n, m;
cin>>n>>m;
int **arr;
bool **visited;
int maximum=0;
/* allocate the array */
arr = (int** )malloc(n * sizeof *arr);
for (int i=0; i<n; i++)
{
arr[i] = (int*)malloc(m * sizeof *arr[i]);
}
/* allocate the visited array */
visited = (bool** )malloc(n * sizeof *visited);
for (int i=0; i<n; i++)
{
visited[i] = (bool*)malloc(m * sizeof *visited[i]);
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>arr[i][j];
}
}
/* dfs call on each cell that has value 1 and is unvisited*/
for(int row=0; row<n; row++){
for(int column=0; column<m; column++){
if(arr[row][column]==1&&isValid(row,column, n, m, visited))
maximum = max(maximum, countConnectedCells(arr, n, m, visited, row, column));
}
}
cout<<maximum<<endl;
/* deallocate the array */
for (int i=0; i<n; i++)
{
free(arr[i]);
}
}
编辑: QUESTION LINK
【问题讨论】:
标签: c++ algorithm depth-first-search