leetcode 54 54. Spiral Matrix(矩阵顺时针绕圈输出)

思路:

我是开辟了一个和原矩阵同样大小的矩阵temp来存放是否输出过的标志位,然后按照向右,向左,向上,向下的顺时针顺序来挨个输出,虽然空间复杂度大了一点,但是好处是思路比较简单,不容易错误。

据说《剑指offer》上有这道题或者类似的题,带我看了剑指offer回来补充补充。

import java.util.ArrayList;
import java.util.List;


public class Solution {
	public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<Integer>();
        int i,j; //i为行数,j为列数
        int count=0;
        
       // result.add(new Integer(matrix[0][0]));
        if(matrix.length == 0)
        	return result;
        int [][]temp = new int[matrix.length][];
        for(i=0;i<matrix.length;i++)
        	temp[i] = new int[matrix[i].length];
        
        
        int row = temp.length;
        for(i=0;i<row;i++)
        	for(j=0;j<temp[i].length;j++)
        		temp[i][j] = 0;
        
        i=j=0;
        //int flag = 1;  //第一个数
        result.add(new Integer(matrix[0][0]));
    	temp[0][0] = 1;
        while(true)
        {
        	while(j+1<temp[i].length && temp[i][j+1] == 0)
        	{  //向右
        		j++;
        		temp[i][j] = 1;
        		result.add(new Integer(matrix[i][j]));
        	}
        	
        	while(i+1 < temp.length && temp[i+1][j] == 0)
        	{//向下
        		i++;
        		temp[i][j] = 1;
        		result.add(new Integer(matrix[i][j]));
        	}  	

        	while(j-1 >= 0 && temp[i][j-1] == 0)
        	{//向左
        		j--;
        		temp[i][j] = 1;
        		result.add(new Integer(matrix[i][j]));
        	}
        	
        	while(i-1 >= 0 && temp[i-1][j] == 0)
        	{//向上
        		i--;
        		temp[i][j] = 1;
        		result.add(new Integer(matrix[i][j]));
        	}
        	
        	if((j+1==temp[i].length || temp[i][j+1] != 0) && (i+1 == temp.length || temp[i+1][j] != 0) && (j-1 < 0 || temp[i][j-1] != 0) && (i-1 < 0 || temp[i-1][j] != 0))
        		break;
        }
            return result;      
    }
	
	public static void main(String args[])
	{
		int i;
		//int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
		int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
		List<Integer> result;
		result = new Solution().spiralOrder(matrix);
		for(i=0;i<result.size();i++)
		{
			System.out.print(result.get(i)+"__");
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值