简体   繁体   中英

Sort the matrix row-wise and column-wise

The solution is available on Geeksforgeeks but the concept is not clear. If I sort all the rows first and then sort the columns or vice-a-versa. the approach seems to work on some test cases. I would like to know if anyone can come up with a test case where this would fail.

Given a matrix, the goal is to sort the matrix row-wise and column-wise such that the increasing order is maintained in both directions.

For example:

enter code here
Input : mat[][] ={4, 1, 3}
                {9, 6, 8}
                {5, 2, 7}
Output : 1 3 4
         2 5 7
         6 8 9

for further reference, refer this link https://www.geeksforgeeks.org/sort-matrix-row-wise-column-wise/

You are right on this, the problem is ill-defined. The solution is not unique, and sorting on rows first and columns second does not give the same result as sorting on columns first and rows second.

Columns, Rows
4 8 2      3 1 2      1 2 3
7 6 9  ->  4 6 5  ->  4 5 6
3 1 5      7 8 9      7 8 9

Rows, Columns
4 8 2      2 4 8      1 3 5
7 6 9  ->  6 7 9  ->  2 4 8
3 1 5      1 3 5      6 7 9

Note how both results are "sorted on rows and columns", ie all items on the same row are sorted, and all items on the same column are sorted.

It is also worth noting that not all solutions are found by sorting in these ways, for instance:

1 4 7
2 5 8
3 6 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM