Advertisement
Old_But_Gold

Untitled

Sep 10th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. package com.epam.rd.autotasks;
  2.  
  3. class Spiral {
  4. static int[][] spiral(int rows, int columns) {
  5. int rowCount = rows;
  6. int colCount = columns;
  7. int[][] matrix = new int[rows][columns];
  8. int left = 0;
  9. int right = colCount - 1;
  10. int top = 0;
  11. int bottom = rowCount - 1;
  12.  
  13. int counter = 1;
  14.  
  15. while (left <= right && top <= bottom)
  16. {
  17. for (int i = left; i <= right; i++)
  18. {
  19. matrix[top][i] = counter++;
  20. }
  21. top++;
  22.  
  23. for (int i = top; i <= bottom; i++)
  24. {
  25. matrix[i][right] = counter++;
  26. }
  27. right--;
  28.  
  29. if (top <= bottom)
  30. {
  31. for (int i = right; i >= left; i--)
  32. {
  33. matrix[bottom][i] = counter++;
  34. }
  35. bottom--;
  36. }
  37.  
  38. if (left <= right)
  39. {
  40. for (int i = bottom; i >= top; i--)
  41. {
  42. matrix[i][left] = counter++;
  43. }
  44. left++;
  45. }
  46. }
  47.  
  48. return matrix;
  49. }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement