Java Accepted recursive solution


  • 0
    H
    public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> res = new ArrayList<Integer>();
    	if (matrix.length == 0 || matrix[0].length == 0) return res;
    	goRight(res, matrix, 0, 0, matrix.length - 1, matrix[0].length - 1);
    	return res;
    }
    private void goRight(List<Integer> res, int[][] matrix, int curRowMin, int curColMin, int curRowMax, int curColMax){
    	for (int n = curColMin; n <= curColMax; n++) 
    		res.add(matrix[curRowMin][n]);
    	if (++curRowMin > curRowMax) return;
    	goDown(res, matrix, curRowMin, curColMin, curRowMax, curColMax);
    }
    private void goDown(List<Integer> res, int[][] matrix, int curRowMin, int curColMin, int curRowMax, int curColMax){
    	for (int m = curRowMin; m <= curRowMax; m++) 
    		res.add(matrix[m][curColMax]);
    	if (curColMin > --curColMax) return;
    	goLeft(res, matrix, curRowMin, curColMin, curRowMax, curColMax);
    }
    private void goLeft(List<Integer> res, int[][] matrix, int curRowMin, int curColMin, int curRowMax, int curColMax){
    	for (int n = curColMax; n >= curColMin; n--) 
    		res.add(matrix[curRowMax][n]);
    	if (curRowMin > --curRowMax) return;
    	goUp(res, matrix, curRowMin, curColMin, curRowMax, curColMax);
    }
    private void goUp(List<Integer> res, int[][] matrix, int curRowMin, int curColMin, int curRowMax, int curColMax){
    	for (int m = curRowMax; m >= curRowMin; m--) 
    		res.add(matrix[m][curColMin]);
    	if (++curColMin > curColMax) return;
    	goRight(res, matrix, curRowMin, curColMin, curRowMax, curColMax);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.