dfs-skiing

Description
Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。可是为了获得速度,
滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机
来载你。Michael想知道载一个区域中最长底滑坡。区域由一个二维数组给出。数组
的每个数字代表点的高度。下面是一个例子
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例中,
一条可滑行的滑坡为24-17-16-1。当然25-24-23-…-3-2-1更长。事实上,这是最长的一条。

Input
第一行表示有几组测试数据,输入的第二行表示区域的行数R和列数C
(1 <= R,C <= 100)。
下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
后面是下一组数据;

Output
输出最长区域的长度。

Sample Input
1
5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

Sample Output
25

解题思路 :对每个点进行遍历,遍历到一个点的时候,判断这个点上下左右比这个点小的点,只要比这个点小,就进行搜索,最后找出最长的那一条即可。还是不懂得话可以看这个图解

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

int t,r,c,temp,MAXN;//t代表测试组数,r,c分别为行数,列数,temp用来记录搜索结果
const int m[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//数组m代表上下左右四个方向

struct Node
{
    int a;//a用于接收数据
    int b;//b用于记录经过每个点的路径长度
};
Node l[105][105];

int dfs(int currow,int curcol)
{
    if(l[currow][curcol].b)//如果这个点已经被搜索过,直接返回即可
        return l[currow][curcol].b;
        
    int row,col,maxn=0;//row和col用于记录四周点的下标
    for(int i=0;i<4;i++)
    {
        row=currow+m[i][0];//这里不太懂的话可以理解为将下标的行数或者列数
        col=curcol+m[i][1];//加一或减一
        if(row>0 && row <= r && col > 0 && col <= c && l[row][col].a<l[currow][curcol].a){
        //下标不能越界,并且要寻找比这个点小的值进行搜索
        temp=dfs(row,col);
        maxn=maxn>temp?maxn:temp;
        }
    }
    l[currow][curcol].b=maxn+1;//别忘了加一,因为搜索的时候并没有算上这个点
    return maxn+1;
}

int main()
{
    cin>>t;
    while(t--)
    {
        MAXN=0;
        cin>>r>>c;
        for(int i=1;i<=r;i++)
            for(int j=1;j<=c;j++)
            {
                cin>>l[i][j].a;
                l[i][j].b=0;//将b中的数据初始化
            }
        for(int i=1;i<=r;i++)
        {
            for(int j=1;j<=c;j++)
            {
                temp=dfs(i,j);
                MAXN = MAXN > temp ? MAXN : temp;
            }
        }
        cout<<MAXN<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42891420/article/details/87519705
dfs