Simple Java solution, also works for Spiral Matrix


  • 1
    X
    public int[][] generateMatrix(int n) {
        int[][] rst = new int[n][n];
    	if (n == 0) return rst;
    	int row = 0, col = -1, m = n, count = 0;
    	while (true) {
    		for (int i = 0; i < n; i++) rst[row][++col] = ++count;
    		if (--m == 0) break;
    		for (int i = 0; i < m; i++) rst[++row][col] = ++count;
    		if (--n == 0) break;
    		for (int i = 0; i < n; i++) rst[row][--col] = ++count;
    		if (--m == 0) break;
    		for (int i = 0; i < m; i++) rst[--row][col] = ++count;
    		if (--n == 0) break;
    	}
    	return rst;
    }

Log in to reply
 

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