`
huntfor
  • 浏览: 201179 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Spiral Matrix II

 
阅读更多

新博文地方:[leetcode]Spiral Matrix II

 

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

 好在这道题是n * n矩阵,如果是m * n就复杂了。

女朋友不是计算机专业,只会一点C,不会java,说我的代码注释太少,她看不懂....

算法思想:

以n == 4 为例:

[1, 2, 3, 4]
[12, 13, 14, 5]
[11, 16, 15, 6]
[10, 9, 8, 7]

 result[0][0]是表示第一圈的loop的起点,result[1][1] == 13表示第二层loop的起点

  public int[][] generateMatrix(int n) {
	        int index = 1;
	        int[][] result = new int[n][n];
	        int loop = n % 2 == 0 ? n / 2 : (n / 2) + 1 ;//loop means the count of loop
	        for(int i = 0 ; i < loop; i++){
	        	for(int j = i; j < n - i; j++){//set values of upper row of matrix 
	        		result[i][j] = index++;
	        	}
	        	for(int j = i; j < n - i; j++){//set values of right column of matrix
	        		if(result[j][n - i - 1] == 0){// the first element has already been set.
	        			result[j][n - i - 1] = index++;
	        		}
	        	}
	        	for(int j = n - i - 1; j >= 0; j--){//set values of bottom row of matrix 
	        		if(result[n - i - 1][j] == 0){
	        			result[n - i - 1][j] = index++;
	        		}
	        	}
	        	for(int j = n - i - 1; j >= 0; j--){//set values of left column of matrix
	        		if(result[j][i] == 0){
						result[j][i] = index++;
	        		}
	        	}
	        }
	        return result;
	    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics