LintCode 374-螺旋矩阵 状态机

来源:互联网 发布:淘宝全屏首页怎么做 编辑:程序博客网 时间:2024/05/21 17:44

使用状态机的思路,运用四个状态来回切换,并用count计算步长最终退出。

 static public List<Integer> spiralOrder(int[][] matrix) {        // Write your code here        List<Integer> ret = new ArrayList<>();        if (matrix.length == 0) return ret;        int i = 0;        int j = 0;        int state = 2;        int maxstep = matrix.length * matrix[0].length;        int count = 0;        final int TURNLEFT = 1, TURNRIGHT = 2, TURNUP = 3, TURNDOWM = 4;//定义了四种状态        int visited[][] = new int[matrix.length][matrix[0].length];//定义一个已走过的矩阵        while (count < matrix.length * matrix[0].length) {            int temp = matrix[i][j];            count++;//每走一次都加一            switch (state) {                case TURNLEFT: {                    ret.add(temp);                    visited[i][j] = 1;                    if (j == 0 || visited[i][j - 1] == 1) {                        i--;                        state = TURNUP;                    }                    else {                        j--;                        state = TURNLEFT;                    }                    break;                }                case TURNRIGHT: {                    ret.add(temp);                    visited[i][j] = 1;                    if (j + 1 == matrix[0].length || visited[i][j + 1] == 1) {                        state = TURNDOWM;                        i++;                    }                    else {                        j++;                        state = TURNRIGHT;                    }                    break;                }                case TURNUP: {                    ret.add(temp);                    visited[i][j] = 1;                    if (i == 0 || visited[i - 1][j] == 1) {                        j++;                        state = TURNRIGHT;                    }                    else {                        i--;                        state = TURNUP;                    }                    break;                }                case TURNDOWM: {                    ret.add(temp);                    visited[i][j] = 1;                    if (i + 1 == matrix.length || visited[i + 1][j] == 1) {                        j--;                        state = TURNLEFT;                    }                    else {                        i++;                        state = TURNDOWM;                    }                    break;                }            }        }    return ret;    }
原创粉丝点击