Suppose you have a n x m
grid, and a pointer starting at (0,0)
, and the only operations you can do to the array, are:
- Read the value of the current cell and the 4 cells around it (wrapping around the edges)
- Move the pointer one space in a specified direction (wrapping around the edges)
- Swap the values of the current cell with the one next to it in a specified direction (not wrapping around the edges)
What would be an efficient algorithm using these rules to move around the values such that every row and every column is individually sorted in ascending order?
E.g. if you started with the grid
4 5 2 2
1 3 6 4
some valid final arrangements would be
1 2 2 3
4 4 5 6
1 2 3 5
2 4 4 6