对一个3*4方格进行深度优先搜索联通块,有一个缺点是有一种联通快搜索不到。
#include <iostream>
#include <cmath>
using namespace std;
int m = 3, n = 4, sum = 0;
int pic[3][4];
bool visit[3][4] = { false };
void dfs(int i, int j, int cnt)
{
if (i < 0 || i >= m || j < 0 || j >= n)
{
return;
}
if (visit[i][j] == true)
{
return;
}
// pic[i][j] = cnt;
visit[i][j] = true;
if (cnt == 5)
{
sum++;
return;
}
for (int i2 = -1; i2 <= 1; i2++)
{
for (int j2 = -1; j2 <= 1; j2++)
{
int abs_ij = abs(i2) + abs(j2);
if (abs_ij != 2 && abs_ij != 0 && !visit[i+i2][j+j2])
{
// visit[i2][j2] = true;
dfs(i + i2, j + j2, cnt + 1);
visit[i+i2][j+j2] = false;
}
}
}
}
int main()
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
pic[i][j] = 0;
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
int cnt = 0;
dfs(i, j, cnt + 1);
}
}
cout << "sum: " << sum << endl;
return 0;
}