Guest User

Untitled

a guest
Feb 13th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. using System;
  2.  
  3. class Solution
  4. {
  5. public static List<int> Spiral(int[,] matrix)
  6. {
  7. List<int> res = new List<int>();
  8. if(matrix==null)
  9. return res;
  10. int[,] dir = new int[4,2] {{0,1},{1,0},{0,-1},{-1,0} };
  11.  
  12. int rows = matrix.GetLength(0);
  13. int cols = matrix.GetLength(1);
  14.  
  15. if(rows ==0 || cols==0)
  16. return res;
  17.  
  18. int top=0,bottom= rows-1,left=0,right=cols-1;
  19.  
  20. int total =rows*cols;
  21. int k=0;
  22. int x=0,y=0;
  23. res.Add(matrix[x,y]);
  24. total--;
  25.  
  26. while(total>0)
  27. {
  28. int newX = x + dir[k,0];
  29. int newY = y + dir[k,1];
  30.  
  31. //check valididty
  32. if(newX >=top && newX <=bottom && newY >=left && newY <=right)
  33. {
  34. x = newX;
  35. y=newY;
  36. res.Add(matrix[x,y]);
  37. total--;
  38. }
  39. else
  40. {
  41. switch(k)
  42. {
  43. case 0:
  44. top++;
  45. break;
  46. case 1:
  47. right--;
  48. break;
  49. case 2:
  50. bottom--;
  51. break;
  52. case 3:
  53. left++;
  54. break;
  55. }
  56.  
  57. k = (k+1)%4;
  58. }
  59.  
  60. return res;
  61. }
  62. }
  63.  
  64. static void Main(string[] args)
  65. {
  66. for (var i = 0; i < 5; i++)
  67. {
  68. Console.WriteLine("Hello, World");
  69. }
  70. }
  71. }
Add Comment
Please, Sign In to add comment