Saturday, October 14, 2017

#codingexercise
In a rowwise and columnwise sorted matrix, enumerate the elements in ascending order


There is a front that moves from the top left corner to the bottom right. Element along the front are guaranteed to include the minimum. Since the front only moves one cell down or to the right, the element along the zig zag shape of the front are easy to enumerate to pick out the minimum at any step.
void PrintSerialized(int[ , ] A, int rows, int cols)
{
if ( A== null || rows == 0 || cols == 0) return;

var items = new List<Tuple<int,int>>();
items.Add(new Tuple<int,int>(0,0));

while ( items.Count != 0 )
{

// print current min
var item = RemoveMinValue(items);
Console.WriteLine(item.GetValue());

// add next candidates
var down = new Tuple<int,int>(item.first+1, item.second);
var right = new Tuple<int,int>(item.first,item.second+1);
if (IsValid(down) && items.Contains(down) == false)
    items.Add(down);
if (IsValid(right) && items.Contains(right) == false)
    items.Add(right);
}
Console.WriteLine(A[r,c]);
}


5  10   12  14
6  11  13   19
7  15  22  29
9  25  32  39

No comments:

Post a Comment