All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0054_spiral_matrix.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0001_0100.s0054_spiral_matrix;

// #Medium #Top_Interview_Questions #Array #Matrix #Simulation
// #2022_02_19_Time_0_ms_(100.00%)_Space_42.4_MB_(9.84%)

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

public class Solution {
    public List spiralOrder(int[][] matrix) {
        List list = new ArrayList<>();
        int r = 0;
        int c = 0;
        int bigR = matrix.length - 1;
        int bigC = matrix[0].length - 1;
        while (r <= bigR && c <= bigC) {
            for (int i = c; i <= bigC; i++) {
                list.add(matrix[r][i]);
            }
            r++;
            for (int i = r; i <= bigR; i++) {
                list.add(matrix[i][bigC]);
            }
            bigC--;
            for (int i = bigC; i >= c && r <= bigR; i--) {
                list.add(matrix[bigR][i]);
            }
            bigR--;
            for (int i = bigR; i >= r && c <= bigC; i--) {
                list.add(matrix[i][c]);
            }
            c++;
        }
        return list;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy