leetCode 54.Spiral Matrix(螺旋矩阵) 解题思路和方法

Spiral Matrix


Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].


思路:螺旋数组,须要控制输出方向。我的实现是定义一个boolean数组,与数组大小同样,数据初始全为false.然后定义一个int变量表示方向,碰到数据边界或者下一数据为true,则改变方向。直到越界或者所有为true。结束循环。

详细代码例如以下:

public class Solution {
    public List<Integer> spiralOrder(int[][] a) {
    	List<Integer> list = new ArrayList<Integer>();
    	if(a.length == 0 || a[0].length == 0){
    		return list;
    	}
        int i = 0;//行
        int j = 0;//列
        boolean[][] b = new boolean[a.length][a[0].length];

        int o = 0;//表示方向,0:右;1:下;2:左。3:上
        
        //在范围内循环。超出范围结束
        while(i < a.length && i >= 0 && j < a[0].length && j >= 0){
            if(b[i][j]){//假设已所有走完,结束循环
                break;
            }
            
            list.add(a[i][j]); //加入结果
            b[i][j] = true;//已加入的标记为true,表示已经加入
            
            switch(o){
                case 0://往右走的方向
                    if(j == a[0].length - 1 || b[i][j+1]){
                        o = 1;//走到最右或者已标记,方向往下走
                        i++;
                    }else{
                        j++;
                    }
                    break;
                    
                case 1:
                    if(i == a.length - 1 || b[i+1][j]){
                        o = 2;//走到最下或者已标记,方向往左走
                        j--;
                    }else{
                        i++;
                    }
                    break;
                case 2:
                    if(j == 0 || b[i][j-1]){
                        o = 3;//走到最左或者已标记。方向往上走
                        i--;
                    }else{
                        j--;
                    }
                    break;
                case 3:
                    if(i == 0 || b[i-1][j]){
                        o = 0;//走到最上或者已标记。方向往右走
                        j++;
                    }else{
                        i--;
                    }
                    break;
            }
        }
        return list;
    }
}


原文地址:https://www.cnblogs.com/wzjhoutai/p/6895886.html