簡體   English   中英

逆時針旋轉矩陣 M*N 的每個環

[英]Rotate each ring of the matrix M*N anticlockwise

我無法逆時針旋轉M*N矩陣。 我的代碼適用於3*3矩陣,但是當我嘗試任何其他情況時,它不起作用假設我是為4*4矩陣做的,那么只有外部元素在旋轉,內部 4 個元素(即 6,7,10 ,11) 不旋轉。 我的輸入是 1-16 個數字作為4*4矩陣:

{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }
static void antiRotateMatrix(int m, int n, int mat[][]) {
    int row = 0, col = n - 1;
    int prev, curr;
    while (row < m && col < n) {
        if (row + 1 == m || col - 1 == 0) {
            break;
        }
        prev = mat[row + 1][col];
        for (int i = col; i >= 0; i--) {
            curr = mat[row][i];
            mat[row][i] = prev;
            prev = curr;
        }
        row++;

        for (int i = row; i < m; i++) {
            curr = mat[i][0];
            mat[i][0] = prev;
            prev = curr;
        }
        n--;

        if (row < m) {
            for (int i = n - 2; i <= col; i++) {
                curr = mat[m - 1][i];
                mat[m - 1][i] = prev;
                prev = curr;
            }
        }
        m--;
        if (col <= n) {
            for (int i = m - 1; i >= row; i--) {
                curr = mat[i][col];
                mat[i][col] = prev;
                prev = curr;
            }
        }
        col++;
    }
    for (int i = 0; i <= 3; i++) {
        for (int j = 0; j <= 3; j++)
            System.out.print(mat[i][j] + " ");
        System.out.print("\n");
    }
}

對於4*4我應該得到

{{2,3,4,8},{1,7,11,12},{5,6,10,16},{9,13,14,15}}

但我得到

{{2,3,4,8},{1,6,7,12},{5,10,11,16},{9,13,14,15}}

逆時針旋轉每層M*N矩陣元素:

for z in range(r):#r = n times to rotate your element of each layer
    top = 0
    bottom = len(matrix)-1

    left = 0
    right = len(matrix[0])-1

    while left < right and top < bottom: # anticlockwise rotation of each layer.
        prev = matrix[top+1][right]
        for i in range(right,left-1,-1):
            curr = matrix[top][i]
            matrix[top][i]= prev
            prev =curr
        top += 1
        for i in range(top,bottom+1):
            curr = matrix[i][left]
            matrix[i][left]=prev
            prev=curr
        left += 1
        for i in range(left,right+1):
            curr =matrix[bottom][i]
            matrix[bottom][i]=prev
            prev = curr
        bottom -=1
        for i in range(bottom,top-1,-1):
            curr = matrix[i][right]
            matrix[i][right]=prev
            prev = curr
        right -=1

順時針轉至https://www.geeksforgeeks.org/rotate-matrix-elements/

我希望您可以將此#python代碼應用於#java ,邏輯是相同的。 或者在hackerrank中選擇python。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM