Leetcode P0059"Spiral Matrix II" 题解

2020/08/27 Leetcode

博文中会简要介绍Leetcode P0059题目分析及解题思路。

“Spiral Matrix II”是p0054的变形题,基本思路一致。

Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

以下是Java的题解代码实现。

class Solution {
    public int[][] generateMatrix(int n) {
        boolean[][] visited = new boolean[n][n];
        int[][] matrix = new int[n][n];
        int count = 1, r = 0, c = 0, di = 0;
        while (count <= n*n) {
            matrix[r][c] = count;
            visited[r][c] = true;
            
            if (this.isRequiredToTurn(visited, r+dr[di], c+dc[di], n, n))
                di = (di+1)%4;
            
            r += dr[di];
            c += dc[di];
            ++count;
        }
        
        return matrix;
    }
    
    private int[] dr = new int[] {0, 1, 0, -1};
    private int[] dc = new int[] {1, 0, -1, 0};
    
    private boolean isRequiredToTurn(boolean[][] visited, int nextRow, int nextCol, int row, int col) {
        if (nextRow < row && nextRow >= 0 
            && nextCol < col && nextCol >= 0 
            && !visited[nextRow][nextCol]) {
            return false;
        }
        
        return true;
    }
}

Search

    Table of Contents