如果能把杨大哥这段代码理解透彻 那么图论那一节应该有了个很好的认识

梅尚程荀
马谭杨奚
程序代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node_struct
{
int height;
int signal;
}node;
int SIGNAL = 1;
int result = 0;
int perfect = 0;
void find_result(node *last, int n)
{
int i;
for (i=0; i<n; i++)
if (0==last[i].signal) result++;
}
void find_perfect(int (*scope)[2], int j, int n)
{
int start = -1, last = 0, i;
while (last!=n)
{
for (i=0; i<j; i++)
if (scope[i][0]<=start+1&&scope[i][1]>last) last = scope[i][1];
start = last;
perfect++;
}
}
int find_target(node *line, int n)
{
static int i = 0;
if (1==n)
{
if (0==line[0].signal) return 0;
else return -1;
}
for (; i<n; i++)
{
if (0==line[i].signal)
{
if (i==0)
{
if (line[i].height>=line[i+1].height) return i;
}
else if (i==n-1)
{
if (line[i].height>=line[i-1].height) return i;
}
else if (line[i].height>=line[i-1].height&&line[i].height>=line[i+1].height)
return i;
}
}
return -1;
}
void find_answer(node *store, int id, int m, int n)
{
int i = id/n, j = id%n;
if (store[id].signal == SIGNAL) return;
store[id].signal = SIGNAL;
if (i!=m-1&&store[id].height>store[id+n].height) find_answer(store, id+n, m, n);
if (j!=n-1&&store[id].height>store[id+1].height) find_answer(store, id+1, m, n);
if (j!=0&&store[id].height>store[id-1].height) find_answer(store, id-1, m, n);
if (i!=0&&store[id].height>store[id-n].height) find_answer(store, id-n, m, n);
}
int main()
{
int M, N, i=0, j=0, k=0, t, (*scope)[2], flag=0;
node *store, *last;
scanf("%d%d",&M,&N);
store = (node *)malloc(M*N*sizeof(node));
scope = (int (*)[2])malloc(sizeof(int)*2*N);
for (t=M*N,i=0; i<t; i++) store[i].signal = 0,scanf("%d",&store[i].height);
last = store+(M-1)*N;
for (i=find_target(store,N); i>=0; i=find_target(store,N))
{
find_answer(store,i,M,N);
for (flag=0,k=0; k<N; k++)
{
if (flag==0&&last[k].signal==SIGNAL) flag=1, scope[j][0] = k;
if (flag==1&&last[k].signal!=SIGNAL)
{
scope[j][1] = k-1;
break;
}
else if (flag==1&&k==N-1)
scope [j][1] = N-1;
}
j++, SIGNAL++;
}
find_result(last,N);
free(store);
if (result>0)
{
printf("%d\n%d\n",0,result);
return 0;
}
find_perfect(scope,j,N-1);
printf("%d\n%d\n",1,perfect);
return 0;
}
