下面是我编写的一个简单算法,用于递归访问网格中所有单元格的邻居:
#include <stdio.h>
#include <string.h>
#define N 2
// Tracks number of times a cell has been visited.
static int visited[N][N];
// If 1, means a cell has already been visited in the current path
// through the grid.
static int been[N][N];
void visit(int x, int y, int level)
{
int i;
int j;
visited[x][y] += 1;
been[x][y] = 1;
for (i = -1; i < 2; i++)
for (j = -1; j < 2; j++)
{
// Neighbor has to be in the grid and not already visited
// in the current path to be visited.
if (x + i > -1 && x + i < N && y + j > -1 && y + j < N)
{
if (been[x + i][y + j] != 1)
{
visit(x + i, y + j, level + 1);
}
}
}
been[x][y] = 0;
}
void main(void)
{
int x;
int y;
int total;
// Initialization.
for (x = 0; x < N; x++)
for (y = 0; y < N; y++)
{
visited[x][y] = 0;
been[x][y] = 0;
}
// Algorithm.
for (x = 0; x < N; x++)
for (y = 0; y < N; y++)
{
visit(x, y, 0);
}
// Print results.
total = 0;
for (x = 0; x < N; x++)
for (y = 0; y < N; y++)
{
printf("x: %d, y: %d, visited: %d\n", x, y, visited[x][y]);
total += visited[x][y];
}
printf("N: %d, total: %d\n", N, total);
}
我很好奇这个算法的顺序。当我用N = 2运行时,输出为:
x: 0, y: 0, visited: 16
x: 0, y: 1, visited: 16
x: 1, y: 0, visited: 16
x: 1, y: 1, visited: 16
N: 2, total: 64
当我用N = 3运行时,我得到:
x: 0, y: 0, visited: 1373
x: 0, y: 1, visited: 1037
x: 0, y: 2, visited: 1373
x: 1, y: 0, visited: 1037
x: 1, y: 1, visited: 665
x: 1, y: 2, visited: 1037
x: 2, y: 0, visited: 1373
x: 2, y: 1, visited: 1037
x: 2, y: 2, visited: 1373
N: 3, total: 10305
我很惊讶地看到3x3网格的中间访问次数最少且角落访问次数最多。我认为角落的访问次数最少,因为它们只有3个邻居,而网格中间有8个。
思想?
答案 0 :(得分:0)
3x3网格中有许多路径。
一个单元格共有的两条路径只会增加这些单元格的“已访问”计数器一次。例如,路径A-B-C-D和A-B-C-E仅增加A,B和C一次。您的代码并不真正计算不同路径中的访问次数 - 要做到这一点,您需要替换
void visit(int x, int y, int level) {
...
visited[x][y] += 1;
...
visit(x + i, y + j, level + 1);
...
}
带
int visit(int x, int y, int level) {
...
int child_paths = 1; // do not increment visited[x][y] yet
...
child_paths += visit(x + i, y + j, level + 1);
...
visited[x][y] += child_paths;
return child_paths;
}