洛谷P1434 [SHOI2002]滑雪

链接:https://www.luogu.com.cn/problem/P1434

C语言:

#include <stdio.h>
#include <stdlib.h>

int f[105][105], h[105][105], vis[105][105];
int fx[4][2] = {{0, 1}, {0, -1},{1, 0},{-1, 0}};

int max(int x, int y)
{
    if (x > y)
        return x;
    else
        return y;
}

int dfs(int x, int y, int n, int m)
{
    int i, j, x1, y1;

    vis[x][y] = 1;
    for (i = 0; i < 4; i++)
    {
        x1 = x + fx[i][0];
        y1 = y + fx[i][1];
        if (x1 <= 0 || x1 > n || y1 <= 0 || y1 > m)
            continue;
        if (h[x1][y1] < h[x][y])
        {
            if (vis[x1][y1] == 0)
            {
                f[x1][y1] = dfs(x1, y1, n, m);
            }
            f[x][y] = max(f[x][y], f[x1][y1] + 1);
        }
    }
    return f[x][y];
}

int main()
{
    int n, m, i, j, ans = 0;

    scanf("%d%d", &n, &m);
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= m; j++)
        {
            scanf("%d", &h[i][j]);
            f[i][j] = 1;
            vis[i][j] = 0;
        }
    }

    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= m; j++)
        {
            ans = max(ans, dfs(i, j, n, m));
        }
    }
    printf("%d\n", ans);

    return 0;
}

python:

输入最好用int()

n, m = s1.split(' ')
n = int(n)
m = int(m)

代码:

def dfs(x, y):
    global f, h, vis, n, m
    fx = [[0, 1], [0, -1], [-1, 0], [1, 0]]

    vis[x][y] = 1
    for i in range(4):
        x1 = x + fx[i][0]
        y1 = y + fx[i][1]
        if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m:
            continue
        if h[x1][y1] < h[x][y]:
            if vis[x1][y1] == 0:
                f[x1][y1] = dfs(x1, y1)
            f[x][y] = max(f[x][y], f[x1][y1] + 1)
    return f[x][y]

s1 = input()
n, m = s1.split(' ')
n = int(n)
m = int(m)
h = []
for i in range(n):
    s1 = input()
    s = s1.split(' ')
    for j in range(m):
        s[j] = int(s[j])
    h.append(s)

f = [[1 for i in range(m + 5)] for j in range(n + 5)]
vis = [[0 for i in range(m + 5)] for j in range(n + 5)]

ans = 0
for i in range(n):
    for j in range(m):
        if vis[i][j] == 0:
            ans = max(ans, dfs(i, j))
print(ans)

 

上一篇:洛谷P2055 [ZJOI2009]假期的宿舍 二分图 匈牙利算法


下一篇:JAVA猜年龄;