- To
注意题目中给的数据的范围
, to determine the size of an array, or else find the cause of the timeout to no avail
step
- The initial point is added to the team next to the search
- while (head <tail) to start the cycle
- Each cycle is determined around 4 points
for(int i=0;i<4;i++)
- To determine whether cross-border and came to decide whether to join the ranks of go
- After the cycle is completed for each, to be in the ranks of the head, in a increase
head++
example
- The largest islands
Description
An ocean area has a number of islands, find the largest island in the area.
With a 0 and contains some non-empty one-dimensional array to represent this area, which represents an area of land 1, 0 represents water. You can assume that the four edges of the two-dimensional matrix are surrounded by water.
Find a given two-dimensional array in the largest island in the area. (If there are no islands, the area is returned to 0.)
Input
The first line of two integers nm (n <= 100 m < = 100)
the next input two-dimensional array of n rows and m columns.
Output
The largest island of the output area (if not the island, the area returns to 0).
Sample Input
4 5
1 0 0 1 1
1 0 1 1 0
0 1 0 0 0
1 1 0 0 1
Sample Output
4
- answer
#include <iostream>
using namespace std;
struct note{
int x;
int y;
};
int nx[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int main()
{
// 超时原因可能是数组太小
int n,m,dx,dy,mm=0;
int data[101][101];
note que[10000];
int head,tail;
int area;
cin >> n >> m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d",&data[i][j]);
}
}
// 搜索
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(data[i][j]==1){
data[i][j] = 0;
head=0,tail=0;
que[tail].x = i;
que[tail].y = j;
tail++;
area = 1;
while(head < tail){
for(int k=0;k<4;k++){
dx = que[head].x + nx[k][0];
dy = que[head].y + nx[k][1];
if(data[dx][dy]==0) continue;
if(dx >=0 && dy>=0 && dx < n && dy <m){
data[dx][dy] = 0;
que[tail].x = dx;
que[tail].y = dy;
tail++;
area++;
}
}
head++;
}
if(area>mm){
mm = area;
}
}
}
}
cout << mm << endl;
return 0;
}