I would use some sort of fill-like algorithm or path-finding algorithms like A *. Start in the upper left corner (value 1), output it and "expand" to the right and bottom - add their values โโ(2 and 5) to the list. Both of them will be greater than 1. Now print the smallest value from your list (value 2) and expand it. You will get 4 and 7 added to your list, pin 4 and โexpandโ it, etc.
Note that while maintaining the sorted list, you can instantly display the smallest element and even display several โrunsโ of consecutive values โโat once (for example, 10,11,12). Thus, the pseudo code will be:
// array a[y][x] // list L - ordered insertion, additionally stores matrix indices of values add a[0][0] to L loop until L is empty output first element of L remove first element of L and add its right and bottom neighbors (if any) to L loop end
EDIT: Here's a working implementation of C.
#include <stdio.h>
Pay attention to the comment on the length of the list. I'm not sure how big the list can get, but I think COLS+ROWS
should be enough to look at this worst case:
1 3 5 7 9 .. 2 yyyy 4 yxxx 6 yxxx 8 yxxx . .
If all border elements are less than the smallest y
value, you will get a list full of y
values โโin the process, which lasts (ROWS - 1) + (COLS - 1)
.
Looking at such worst cases, I think this is not the most effective solution, but I think it is elegant and concise, nonetheless.
schnaader
source share