Pku 3620解題報告
一、原題
Description
Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of water. His insurance agency will only repay him, however, an amount depending on the size of the largest "lake" on his farm.
The farm is represented as a rectangular grid with N (1 ≤ N ≤ 100) rows and M (1 ≤ M ≤ 100) columns. Each cell in the grid is either dry or submerged, and exactly K (1 ≤ K ≤ N × M) of the cells are submerged. As one would expect, a lake has a central cell to which other cells connect by sharing a long edge (not a corner). Any cell that shares a long edge with the central cell or shares a long edge with any connected cell becomes a connected cell and is part of the lake.
Input
* Line 1: Three space-separated integers: N, M, and K
* Lines 2..K+1: Line i+1 describes one submerged location with two space separated integers that are its row and column: R and C
Output
* Line 1: The number of cells that the largest lake contains.
Sample Input
3 4 5
3 2
2 2
3 1
2 3
1 1
Sample Output
4
二.題意闡述
1.其實本題可以轉化成如下的純數學模型。
2.給出n*m大小的矩陣,初始值全為0;
3.在特定的位置將a[i][j]置成1;
4.求取相連的1個數的最大值。
三.算法
此題看似簡單,但實際上蘊藏玄機。懂得此法的同學將無疑大大提升自己的能力,再將其拓展,則能夠解決一大類問題,此題包含著一個及其重要的數學模型----遞歸搜索(名字是自己取的,不專業請原諒)。
只要設計一個函數,給一個入口參數(I,j),使得運行該函數后,得到與(I,j)方塊相連的方塊數。
然后在用循環,將每一個方塊都找一遍,求出最大值即可。
那個函數,這是本題的精髓,用遞歸的方法,可以讓其自動朝著四周的方向搜索滿足條件的方塊,直到求出與某一格相連的小方塊數目的總數。
其實,我一直想把上回的超級瑪麗做出來,這個題給了我基本的搜索本領。我想,只要我繼續研究下去就一定能解決超級瑪麗的問題了 o(∩_∩)o…
四、解題過程
本來想用循環的方法來做的,可是發現用循環貌似無法結束查找。于是我請教了陳澤怡學長,他提示我用遞歸的方法來解此題,這才使我恍然大悟。用遞歸可以不斷地調用函數體本身,直到結束查找!~
五.程序代碼
#include<iostream>
#include<math.h>
#include<algorithm>
using namespace std;
int a[101][101]={0};
int num;
void search(int i,int j)
{
if(a[i][j]==1)
{
a[i][j]=-1;
num++;
search(i,j+1);
search(i+1,j);
search(i,j-1);
search(i-1,j);
}
}//定義遞歸搜索函數,入口參數為所要調查的小方塊位置
int main()
{
int n,m,k,i,j,x,y,max=0;
cin>>n>>m>>k;
for(i=1;i<=k;i++)
{
cin>>x>>y;
a[x][y]=1;//把要調查的位置置為1;
}
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
num=0;
search(i,j);
if(num>=max)
max=num;
}//用循環的方法將整個矩陣都查找一遍,并求出與某小方塊相連方塊數的最大值;
cout<<max<<endl;//輸出該最大值;
return 0;
}
六.小結
這道題的代碼看上去很短,但是確非常非常的重要,當然 ,這并不代表我完全掌握了這類方法,如果說不是深度或者廣度優先怎么辦,如何用隊列?這是接下來我需要面對和解決的問題…另外,我寫報告的水平有待提高,如果不是知道我的意圖,會有人看得懂這份報告么?ACM講究的是團隊作戰,即使我很優秀 ,也不過是個獨斷獨行的人,這是不能成功的,要想取得成績,先得學會與同學交流。
呵呵 這是我的第一篇結題報告 值得紀念啊 當然還要特別感謝賈瓊學姐哦 O(∩_∩)O~