这是一道深搜求连接块大小的问题
说一下题目吧:
就是输入一个果园的数据,6是起点,1是果树,2是墙,只能上下左右走,求从起点开始走最多能摘多少水果。
收获:学会了利用输出来检查错误,以及回溯后需要封死之前经过的路径。
下面是结果:
附上原码:
#include <iostream>
using namespace std;
int a[100][100] = {0}, n, m, cnt; // 采摘园
int fx[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 需要遍历的四个方向
bool in(int x, int y) //判断是否在果园内
{
return (x >= 1 && x <= n && y >= 1 && y <= m);
}
void dfs(int x, int y)
{
if (a[x][y] == 3) //出口(让回溯时封掉之前的路避免死循环)
return;
a[x][y] = 3;
++cnt;
for (int k = 0; k < 4; k++) // 循环遍历四个方向
{
// printf("x= %d y = %d \n",x,y);
int nextX = x + fx[k][0];
int nextY = y + fx[k][1];
printf("x= %d y = %d \n", x, y);
if (in(nextX, nextY) && a[nextX][nextY] != 2 && a[nextX][nextY] != 3) // 在采摘园内且不为墙,且为没采过的树 (进入条件)
{
dfs(nextX, nextY); // 往下深搜
}
}
}
int main()
{
int i, j, sx, sy;
cin >> n >> m; // 输入采摘园大小
for (i = 1; i <= n; i++) // 创建采摘园
{
for (j = 1; j <= m; j++)
{
cin >> a[i][j];
if (a[i][j] == 6) // 找到起点记录并保存
{
sx = i;
sy = j;
}
}
}
cnt = 0;
dfs(sx, sy);
cout << cnt; // 输出苹果数量
return 0;
}