Stampa di una matrice#8530

Stampa di una matrice (Editoriale)

Leggiamo la matrice di input in un array bidimensionale. Successivamente, stampiamo la sottomatrice di dimensione [1 .. r] \times [1 .. c].

Implementazione dell'algoritmo

Dichiariamo un array bidimensionale.

int m[101][101];

Leggiamo la matrice di input n \times n.

scanf("%d", &n);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
  scanf("%d", &m[i][j]);

Leggiamo i valori e .

scanf("%d %d", &r, &c);

Stampiamo la sottomatrice r \times c.

for (i = 1; i <= r; i++)
{
  for (j = 1; j <= c; j++)
    printf("%d ", m[i][j]);
  printf("\n");
}

Implementazione in Java

import java.util.*;
 
public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m[][] = new int[n][n];
    for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
      m[i][j] = con.nextInt();
    
    int r = con.nextInt();
    int c = con.nextInt();

    for(int i = 0; i < r; i++)
    {
      for(int j = 0; j < c; j++)
        System.out.print(m[i][j] + " ");
      System.out.println();
    }
    con.close();
  }
}

Implementazione in Python

Leggiamo i dati di input.

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
r, c = map(int, input().split())

Stampiamo la sottomatrice r \times c.

for i in range(r):
  for j in range(c):
    print(a[i][j],end = " ")
  print()

Implementazione in Python — sottomatrice

Leggiamo i dati di input.

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
r, c = map(int, input().split())

Estraiamo dalla matrice la sottomatrice r \times c.

res = [row[:c] for row in a[:r]]

Stampiamo la sottomatrice r \times c.

for row in res:
  print(*row)