SHARE
TWEET

Untitled

sweet1cris Sep 14th, 2017 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class SpiralGenerateI {
  2.   // Method 1: Recursive Generate.
  3.   public int[][] spiralGenerate(int n) {
  4.     // Assumptions: n >= 0.
  5.     int[][] matrix = new int[n][n];
  6.     if (n == 0) {
  7.       return matrix;
  8.     }
  9.     recursiveGenerate(matrix, 0, n, 1);
  10.     return matrix;
  11.   }
  12.  
  13.   private void recursiveGenerate(int[][] matrix, int offset, int size, int num)
  14. {
  15.     // the base case is when there is only 0 or 1 element left.
  16.     if (size == 0) {
  17.       return;
  18.     }
  19.     // do not forget this base case.
  20.     if (size == 1) {
  21.       matrix[offset][offset] = num;
  22.       return;
  23.     }
  24.     for (int i = 0; i < size - 1; i++) {
  25.       matrix[offset][offset + i] = num++;
  26.     }
  27.     for (int i = 0; i < size - 1; i++) {
  28.       matrix[offset + i][offset + size - 1] = num++;
  29.     }
  30.     for (int i = size - 1; i >= 1; i--) {
  31.       matrix[offset + size - 1][offset + i] = num++;
  32.     }
  33.     for (int i = size - 1; i >= 1; i--) {
  34.       matrix[offset + i][offset] = num++;
  35.     }
  36.     recursiveGenerate(matrix, offset + 1, size - 2, num);
  37.   }
  38.  
  39.   // Method 2: Iterative Generate.
  40.   public int[][] spiralGenerateII(int n) {
  41.     // Assumptions: n >= 0.
  42.     int[][] matrix = new int[n][n];
  43.     if (n == 0) {
  44.       return matrix;
  45.     }
  46.     int start = 0;
  47.     int end = n - 1;
  48.     int num = 1;
  49.     // the base case is there is 0 or 1 element left.
  50.     while (start < end) {
  51.       for (int i = start; i <= end; i++) {
  52.         matrix[start][i] = num++;
  53.       }
  54.       for (int i = start + 1; i <= end - 1; i++) {
  55.         matrix[i][end] = num++;
  56.       }
  57.       for (int i = end; i >= start; i--) {
  58.         matrix[end][i] = num++;
  59.       }
  60.       for (int i = end - 1; i >= start + 1; i--) {
  61.         matrix[i][start] = num++;
  62.       }
  63.       start++;
  64.       end--;
  65.     }
  66.     // do not forget one of the base cases is there is
  67.     // one element left.
  68.     if (start == end) {
  69.       matrix[start][end] = num++;
  70.     }
  71.     return matrix;
  72.   }
  73. }
RAW Paste Data
Top