’‘’时隔多日,再次写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;
}