题目描述:https://pycoder.blog.csdn.net/article/details/125401136
递归,回溯的时候要考虑周全,不然白理解了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct Node {
int x;
int y;
};
int m, n;
int direction[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int dfs(struct Node cur, struct Node target, int map[100][100]) {
struct Node node;
if ((cur.x == target.x) && (cur.y == target.y)) {
return 1;
}
for (int i = 0; i < 4; i++) {
int x = cur.x + direction[i][0];
int y = cur.y + direction[i][1];
if ((x < 0) || (x >= n) || (y < 0) || (y >= m)) {
continue;
}
if (map[y][x] == 1) {
continue;
}
map[cur.y][cur.x] = 1; // 走过的路设为障碍物
node.x = x;
node.y = y;
if (dfs(node, target, map) == 1) {
map[cur.y][cur.x] = 0; // 回溯
return 1;
}
map[cur.y][cur.x] = 0; // 回溯
}
return 0;
}
int main(void) {
int res = 0;
int arr[100][100];
int person_num = 0;
struct Node person[2];
int restaurant_num = 0;
struct Node restaurant[100];
scanf("%d %d", &m, &n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &arr[i][j]);
if (arr[i][j] == 2) {
person[person_num].x = j;
person[person_num++].y = i;
} else if (arr[i][j] == 3) {
restaurant[restaurant_num].x = j;
restaurant[restaurant_num++].y = i;
}
}
}
/*
* 从餐厅出发找person是最好的,以为person确定就是两个人
*/
for (int i = 0; i < restaurant_num; i++) {
if (dfs(restaurant[i], person[0], arr) == 1) {
if (dfs(restaurant[i], person[1], arr) == 1) {
res++;
}
}
}
printf("%d\n", res);
return 0;
}