每日一题00011DFS

’‘’时隔多日,再次写dfs‘’‘

题目:

思路:非常标准的dfs题目。

用标记数组统计图上能去块的就ok了。

代码:

#include <stdio.h>

#define rows 1001
#define cols 1001
int m, n;
int a[rows][cols] = {0};
int v[rows][cols] = {0};
int gcd(int a, int b) {
    if (b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}
void dfs(int x, int y, int rx, int ry) {
    if (x <= 0 || x > n || y <= 0 || y > m || v[x][y] || gcd(a[x][y], a[rx][ry]) <= 1) {
        return;
    }
    v[x][y] = 1;
    dfs(x - 1, y, x, y);
    dfs(x + 1, y, x, y);
    dfs(x, y - 1, x, y);
    dfs(x, y + 1, x, y);
}
int countx(int r, int c) {
    dfs(r, c, r, c);
    int count = 0;
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (v[i][j] == 1) {
                count++;
            }
        }
    }
    printf("%d\n", count);
    return count;
}
int main() {
    scanf("%d %d", &m, &n);
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);
    int r, c;
    scanf("%d %d", &r, &c);
    countx(r, c);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值