Share my AC solution, using recursion.


  • 0
    I
    public class Solution {
        public void helper(int[][] num, int x, int y, int loop, int start) {
            if (loop <= 0) {
                return;
            }
            for (int i = y; i < y + loop; ++i, ++start) {
                num[x][i] = start;
            }
            for (int i = x + 1; i < x + loop; ++i, ++start) {
                num[i][y+loop-1] = start;
            }
            for (int i = y + loop - 2; i > y - 1; --i, ++start) {
                num[x+loop-1][i] = start;
            }
            for (int i = x + loop - 2; i > x; --i, ++start) {
                num[i][y] = start;
            }
            helper(num, x+1, y+1, loop-2, start);
        }
    
        public int[][] generateMatrix(int n) {
            int[][] result = new int[n][n];
            helper(result, 0, 0, n, 1);
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.