Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the order of the following algorithm?
    primarykey
    data
    text
    <p>Below is a simple algorithm that I wrote for recursively visiting all of a cell's neighbors in a grid:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #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 &lt; 2; i++) for (j = -1; j &lt; 2; j++) { // Neighbor has to be in the grid and not already visited // in the current path to be visited. if (x + i &gt; -1 &amp;&amp; x + i &lt; N &amp;&amp; y + j &gt; -1 &amp;&amp; y + j &lt; 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 &lt; N; x++) for (y = 0; y &lt; N; y++) { visited[x][y] = 0; been[x][y] = 0; } // Algorithm. for (x = 0; x &lt; N; x++) for (y = 0; y &lt; N; y++) { visit(x, y, 0); } // Print results. total = 0; for (x = 0; x &lt; N; x++) for (y = 0; y &lt; 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); } </code></pre> <p>I'm curious as to the order of this algorithm. When I run it with N = 2, the output is:</p> <pre><code>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 </code></pre> <p>When I run it with N = 3, I get:</p> <pre><code>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 </code></pre> <p>I was surprised to see the middle of the 3x3 grid visited the least number of times and the corners visited the most. I thought the corners would be visited the least because they have only have 3 neighbors while the middle of the grid has 8.</p> <p>Thoughts?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload