Created
March 17, 2016 06:00
-
-
Save jianminchen/aa7a35df305b05f5d90a to your computer and use it in GitHub Desktop.
Matrix Spiral Print -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//sprial print n x m , n close m, n >> m, assume n is close to m | |
// first row, l -> R | |
// last col, t->b | |
// last row, r->l | |
// first col,b-<t | |
// ask the interviewer: | |
// recusive call | |
// iterative solution | |
// do the work, better idea. | |
public static string spiralPrint(int[][] A) | |
{ | |
if(A.Length == 0 ) return ""; | |
int M = A.Length; | |
int N = A[0].Length; | |
int startCol = 0; | |
int endCol = N-1; | |
//int startRow = 0; | |
//int endRow = N-1; | |
for(int i=0; i< M && startCol> endCol; i++) // row number 1, 2, 3, 4, 5 | |
{ | |
for(int j=startCol; j<= endCol; j++) // l-> R 7 8 9 - fix the bug | |
{ | |
s +=Convert.ToString(A[i][j]); // check row i = 0 | |
} | |
// row number - start i+1, | |
// for(int j= i+1; j< M; i++) // top -> down M ? 14 // bug | |
for(int j= i+1; j< M -i; i++) | |
{ | |
s +=convert.Tostring(A[j][endCol]); // j = 2, 3, work | |
} | |
//for(int j=M-1; j>=0;j--) // right -> left, col - change, row number = M-1 13 12 | |
for(int j = endCol; j>=startCol; j--) | |
//s +=convert.Tostring(A[M-1][j]); // row ok, j decreasing ok M-1? i = 0 | |
s +=convert.Tostring(A[M-1-i][j]); | |
// bottom to up col = 1, row = | |
///for(int j = M-1; j>i; j--) // 11 6 | |
for(int j = M-i-1; j>i; j--) // 11 6 | |
s +=convert.Tostring(A[j][startCol]); // | |
// startRow, endRow | |
startCol++; | |
endCol --; | |
// if(startCol> endCol) | |
// break; | |
} | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment