📌  相关文章
📜  以螺旋形式对角打印矩阵元素

📅  最后修改于: 2021-09-07 02:19:27             🧑  作者: Mango

给定一个维度为N * M的矩阵arr[][]和一个整数K ,任务是以螺旋形式打印从左上角元素到K的矩阵的所有元素。

例子:

处理方法:按照以下步骤解决问题:

  1. 矩阵中对角线的总数为N + M – 1
  2. 以螺旋方式一条一条地穿过对角线。
  3. 对于遍历的每个元素,检查它是否等于K。如果发现为真,则打印该元素并终止。
  4. 否则,打印元素并评估要遍历的下一个索引。如果ij是当前索引:
    • 沿对角线向上移动时, i将递减, j将递增。
    • 沿对角线向下移动时, i将递增, j将递减。
  5. 如果下一个索引不是有效索引,则移动到下一个对角线。
  6. 否则,将当前位置更新到下一个。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if the
// indices are valid or not
bool isValid(int i, int j,
            int N, int M)
{
    return (i >= 0 && i < N
            && j >= 0 && j < M);
}
 
// Function to evaluate the next
// index while moving diagonally up
pair up(int i, int j,
                int N, int M)
{
    if (isValid(i - 1, j + 1, N, M))
        return { i - 1, j + 1 };
    else
        return { -1, -1 };
}
 
// Function to evaluate the next
// index while moving diagonally down
pair down(int i, int j,
                    int N, int M)
{
    if (isValid(i + 1, j - 1, N, M))
        return { i + 1, j - 1 };
    else
        return { -1, -1 };
}
 
// Function to print matrix elements
// diagonally in Spiral Form
void SpiralDiagonal(int N, int M, int K,
                    vector > a)
{
    int i = 0, j = 0;
 
    // Total Number of Diagonals
    // = N + M - 1
    for (int diagonal = 0;
        diagonal < N + M - 1;
        diagonal++) {
 
        while (1) {
 
            // Stop when K is
            // encountered
            if (a[i][j] == K) {
 
                cout << K;
                return;
            }
 
            // Print the integer
            cout << a[i][j] << ", ";
 
            // Store the next index
            pair next;
            if (diagonal & 1) {
 
                next = down(i, j, N, M);
            }
            else {
 
                next = up(i, j, N, M);
            }
 
            // If current index is invalid
            if (next.first == next.second
                && next.first == -1) {
 
                // Move to the next diagonal
                if (diagonal & 1) {
 
                    (i + 1 < N) ? ++i : ++j;
                }
                else {
 
                    (j + 1 < M) ? ++j : ++i;
                }
                break;
            }
 
            // Otherwise move to the
            // next valid index
            else {
 
                i = next.first;
                j = next.second;
            }
        }
    }
}
 
// Driver Code
int main()
{
 
    int N = 5, M = 6, K = 15;
    vector > arr
        = { { 1, 2, 3, 4, 5, 6 },
            { 7, 8, 9, 10, 11, 12 },
            { 13, 14, 15, 16, 17, 18 },
            { 19, 20, 21, 22, 23, 24 },
            { 25, 26, 27, 28, 29, 30 } };
 
    // Function Call
    SpiralDiagonal(N, M, K, arr);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
import java.lang.*;
  
class GFG{
static class pair
{
    int first, second;
    pair(int f, int s)
    {
        this.first = f;
        this.second = s;
    }
}
 
// Function to check if the
// indices are valid or not
static boolean isValid(int i, int j,
                       int N, int M)
{
    return (i >= 0 && i < N &&
            j >= 0 && j < M);
}
  
// Function to evaluate the next
// index while moving diagonally up
static int[] up(int i, int j,
                int N, int M)
{
    if (isValid(i - 1, j + 1, N, M))
        return new int[]{ i - 1, j + 1 };
    else
        return new int[]{ -1, -1 };
}
  
// Function to evaluate the next
// index while moving diagonally down
static int[] down(int i, int j,
                  int N, int M)
{
    if (isValid(i + 1, j - 1, N, M))
        return new int[]{ i + 1, j - 1 };
    else
        return new int[]{ -1, -1 };
}
  
// Function to print matrix elements
// diagonally in Spiral Form
static void SpiralDiagonal(int N, int M,
                           int K, int[][] a)
{
    int i = 0, j = 0;
  
    // Total Number of Diagonals
    // = N + M - 1
    for(int diagonal = 0;
            diagonal < N + M - 1;
            diagonal++)
    {
        while (true)
        {
             
            // Stop when K is
            // encountered
            if (a[i][j] == K)
            {
                System.out.print(K);
                return;
            }
             
            // Print the integer
            System.out.print(a[i][j] + ", ");
             
            // Store the next index
            int[] next;
             
            if ((diagonal & 1) == 1)
            {
                next = down(i, j, N, M);
            }
            else
            {
                next = up(i, j, N, M);
            }
  
            // If current index is invalid
            if (next[0] == next[1] &&
                next[1] == -1)
            {
                 
                // Move to the next diagonal
                if ((diagonal & 1) == 1)
                {
                    if (i + 1 < N)
                        ++i;
                    else
                        ++j;
                }
                else
                {
                    if (j + 1 < M)
                        ++j;
                    else
                        ++i;
                }
                break;
            }
             
            // Otherwise move to the
            // next valid index
            else
            {
                i = next[0];
                j = next[1];
            }
        }
    }
}
  
// Driver code
public static void main (String[] args)
{
    int N = 5, M = 6, K = 15;
    int[][] arr = { { 1, 2, 3, 4, 5, 6 },
                    { 7, 8, 9, 10, 11, 12 },
                    { 13, 14, 15, 16, 17, 18 },
                    { 19, 20, 21, 22, 23, 24 },
                    { 25, 26, 27, 28, 29, 30 } };
                     
    // Function Call
    SpiralDiagonal(N, M, K, arr);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the
# above approach
 
# Function to check if the
# indices are valid or not
def isValid(i, j, N, M):
    return (i >= 0 and i < N and j >= 0 and j < M)
 
# Function to evaluate the next
# index while moving diagonally up
def up(i, j, N, M):
    if(isValid(i - 1, j + 1, N, M)):
        return [i - 1, j + 1 ]
    else:
        return [-1, -1]
 
# Function to evaluate the next
# index while moving diagonally down
def down(i, j, N, M):
    if(isValid(i + 1, j - 1, N, M)):
        return [i + 1, j - 1 ]
    else:
        return [-1, -1]
 
# Function to print matrix elements
# diagonally in Spiral Form
def SpiralDiagonal(N, M, K, a):
    i = 0
    j = 0
 
    # Total Number of Diagonals
    # = N + M - 1
    for diagonal in range(N + M - 1):
 
        while(True):
           
            # Stop when K is
            # encountered
            if(a[i][j] == K):
                print(K, end = "")
                return
               
            # Print the integer
            print(a[i][j], ", ", end="", sep="")
 
            # Store the next index
            next = []
            if((diagonal & 1) == 1):
                next = down(i, j, N, M)
            else:
                next = up(i, j, N, M)
 
            # If current index is invalid
            if(next[0] == next[1] and next[1] == -1):
                 
                # Move to the next diagonal
                if((diagonal & 1) == 1):
                    if(i + 1 < N):
                        i += 1
                    else:
                        j += 1
                else:
                    if(j + 1 < M):
                        j += 1
                    else:
                        i += 1
                break
                 
            # Otherwise move to the
            # next valid index
            else:
                i = next[0]
                j = next[1]
 
# Driver code
N = 5
M = 6
K = 15
arr = [[1, 2, 3, 4, 5, 6 ],
       [ 7, 8, 9, 10, 11, 12],
       [13, 14, 15, 16, 17, 18 ],
       [19, 20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29, 30]]
 
# Function Call
SpiralDiagonal(N, M, K, arr);
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program for the
// above approach
using System;
 
class GFG{
 
// Function to check if the
// indices are valid or not
static bool isValid(int i, int j,
                    int N, int M)
{
    return (i >= 0 && i < N &&
            j >= 0 && j < M);
}
 
// Function to evaluate the next
// index while moving diagonally up
static int[] up(int i, int j, int N, int M)
{
    if (isValid(i - 1, j + 1, N, M))
        return new int[]{ i - 1, j + 1 };
    else
        return new int[]{ -1, -1 };
}
 
// Function to evaluate the next
// index while moving diagonally down
static int[] down(int i, int j, int N, int M)
{
    if (isValid(i + 1, j - 1, N, M))
        return new int[]{ i + 1, j - 1 };
    else
        return new int[]{ -1, -1 };
}
 
// Function to print matrix elements
// diagonally in Spiral Form
static void SpiralDiagonal(int N, int M, int K,
                           int[, ] a)
{
    int i = 0, j = 0;
 
    // Total Number of Diagonals
    // = N + M - 1
    for(int diagonal = 0;
            diagonal < N + M - 1;
            diagonal++)
    {
        while (true)
        {
             
            // Stop when K is
            // encountered
            if (a[i, j] == K)
            {
                Console.Write(K);
                return;
            }
 
            // Print the integer
            Console.Write(a[i, j] + ", ");
 
            // Store the next index
            int[] next;
 
            if ((diagonal & 1) == 1)
            {
                next = down(i, j, N, M);
            }
            else
            {
                next = up(i, j, N, M);
            }
 
            // If current index is invalid
            if (next[0] == next[1] &&
                next[1] == -1)
            {
                 
                // Move to the next diagonal
                if ((diagonal & 1) == 1)
                {
                    if (i + 1 < N)
                        ++i;
                    else
                        ++j;
                }
                else
                {
                    if (j + 1 < M)
                        ++j;
                    else
                        ++i;
                }
                break;
            }
 
            // Otherwise move to the
            // next valid index
            else
            {
                i = next[0];
                j = next[1];
            }
        }
    }
}
 
// Driver code
public static void Main(string[] args)
{
    int N = 5, M = 6, K = 15;
    int[, ] arr = { { 1, 2, 3, 4, 5, 6 },
                    { 7, 8, 9, 10, 11, 12 },
                    { 13, 14, 15, 16, 17, 18 },
                    { 19, 20, 21, 22, 23, 24 },
                    { 25, 26, 27, 28, 29, 30 } };
 
    // Function Call
    SpiralDiagonal(N, M, K, arr);
}
}
 
// This code is contributed by grand_master


输出:

1, 2, 7, 13, 8, 3, 4, 9, 14, 19, 25, 20, 15

时间复杂度: O(N*M)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live