码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_Spiral Matrix II

时间:2015-05-16 10:34:09      阅读:88      评论:0      收藏:0      [点我收藏+]

标签: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 ]
]

思路:

这题看起来是很复杂,做起来也确实挺复杂的。但是呢,这题并不是非常非常难,只是控制逻辑让人很抓狂罢了。

colStart,colEnd,rowStart,rowEnd,num=0

1.colStart<colEnd  为arr[row][colStart]~arr[row][colEnd-1]赋值num++;

2.rowStart<rowEnd 为arr[col][rowStart]~ar[col][rowEnd-1]赋值num++;

3.colEnd>colStart 为arr[rowLen-1-row][colEnd]~arr[rowLen-1-row][colStart+1]赋值num++;

4.rowEnd>rowStart 为arr[colLen-1-col][rowEnd]~arr[colLen-1-col][rowStart+1]赋值num++;

代码:

public int[][] generateMatrix(int n) {
		int matrix[][]=null;
		if(n<0)
	        	return matrix;
		else if(n==0)
		{
			matrix=new int [1][];
			matrix[0]=new int[]{};
		}
		matrix=new int[n][];
		for(int i=0;i<n;i++)
			matrix[i]=new int[n];
        int startNum=1;
        int rows=n,cols=n;
        int x=0,y=0;
        while(x<cols-x&&y<rows-y)
        {
        	int end=cols-x-1;
        	if(x<end)
        	{
        		for(int i=x;i<end;i++)
            		matrix[y][i]=startNum++;
        	}
        	
        	end=rows-y-1;
        	if(y<end)
        	{
        		for(int j=y;j<end;j++)
            		matrix[j][cols-x-1]=startNum++;;
        	}
        	int start=cols-x-1;
        	if(start>x)
        	{
        		for(int i=start;i>x;i--)
            		matrix[rows-y-1][i]=startNum++;;
        	}
        	start=rows-y-1;
        	if(start>y)
        	{
        		for(int j=start;j>y;j--)
            		matrix[j][x]=startNum++;
        	}
        	if(2*x+1==cols&&2*y+1==rows)
        		matrix[y][x]=startNum++;;
        	x++;
        	y++;
        }
        return matrix;
    }


leetcode_Spiral Matrix II

标签:spiral matrix ii

原文地址:http://blog.csdn.net/mnmlist/article/details/45765775

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!