【LeetCode-面試演算法經典-Java實現】【059-Spiral Matrix II(螺旋矩陣II)】,leetcode--java

來源:互聯網
上載者:User

【LeetCode-面試演算法經典-Java實現】【059-Spiral Matrix II(螺旋矩陣II)】,leetcode--java
【059-Spiral Matrix II(螺旋矩陣II)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題

  Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
  For example,
  Given n = 3,
  You should return the following matrix:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

題目大意

  給定一個整數n,產生一個n*n的矩陣,用1-n^2的數字進行螺旋填充。

解題思路

  採用計算產生法,對每一個位置計算對應的數。

代碼實現

演算法實作類別

public class Solution {    public int[][] generateMatrix(int n) {        int[][] result = new int[n][n];        int layer;        int k;        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                layer = layer(i, j, n); // 當前座標外有幾層                // n * n - layer * layer外圍層使用的最後一個數字(也是最大的)                // 座標所在的當前層使用的第一個數字                k = n * n - (n - 2 * layer) * (n - 2 * layer) + 1;                result[i][j] = k;                // (n - 2 * layer - 1):四個(n - 2 * layer - 1)就是(x,y)座標所在層的所有元素個數                if (i == layer) { // 情況一、座標離上邊界最近                    result[i][j] = k + j - layer;                } else if (j == n - layer - 1) { // 情況二、座標離右邊界最近                    result[i][j] = k + (n - 2 * layer - 1) + i - layer;                } else if (i == n - layer - 1) { // 情況三、座標離下邊界最近                    result[i][j] = k + 3 * (n - 2 * layer - 1) - (j - layer);                } else { // 情況三、座標離左邊界最近                    result[i][j] = k + 4 * (n - 2 * layer - 1) - (i - layer);                }            }        }        return result;    }    /**     * 在一個n*n的矩陣中,計算(x,y)座標外有多少層,座標從0開始計算     *     * @param x 橫座標     * @param y 縱座標     * @param n 矩陣大小     * @return 座標外的層數     */    public int layer(int x, int y, int n) {        x = x < n - 1 - x ? x : n - 1 - x; // 計算橫座標離上下邊界的最近距離        y = y < n - 1 - y ? y : n - 1 - y; // 計算縱座標離左右邊界的最近距離        return x < y ? x : y; // 較小的值為座標的外圍層數    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47164439】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.