3 ms·
The author doesn't mention that the grid being initalized is square, and simply describes it as grid[rows][cols]. However, all his solutions are only correct fo
by stirner 10y ago
The author doesn't mention that the grid being initalized is square, and simply describes it as grid[rows][cols]. However, all his solutions are only correct for a square grid.
One solution for arbitrary dimensions could be
for (i = 0; i < rows; ++i) {
grid[i][0] = 0;
grid[i][cols - 1] = 0;
}
for (i = 0; i < cols; ++i) {
grid[0][i] = 0;
grid[rows - 1][i] = 0;
}
- deleted 10y ago[deleted]
- dghf 10y agoYou're updating the corners twice. Not really a problem with a simple assignment, but as no_protocol pointed out elsewhere [0], it could be if you ever wanted to change that to, say, an increment. Replace your second for statement with for (i = 1; i < cols - 1; ++i) { ... and you're golden. [0] https://news.ycombinator.com/item?id=12794235 https://news.ycombinator.com/item?id=12794235
- stirner 10y agoYou're right, my version is unoptimized because I was trying to keep the code neat as in the article. I think that optimizing the code for hypothetical future reuse is a bit premature. You could make a performance argument, but this optimization is going to prevent just 2 memory accesses, which aren't going to matter much compared to all the rest. If I was chasing performance I would start by memset'ing the top and bottom edges since they're contiguous in memory.
- stirner 10y agoMy mistake - the optimization would prevent four memory accesses. Still O(1).