A
matrix of size n × n
is given, referred to as the [1 .. n]
× [1 .. n] array. For given r and c,
print a submatrix of size [1 .. r] × [1 .. c], consisting of the first r rows and the first c
columns of the original matrix.
Input.
The first line contains an integer n (1 ≤ n ≤ 100).
The next n lines contain the elements of an n × n matrix. The last line contains two
integers r and c (1 ≤ r, c
≤ n). All matrix elements do
not exceed 100 in absolute value.
Output.
Print a submatrix of size r × c, consisting of the first r rows and the first c
columns of the original matrix.
Sample input 1 |
Sample output 1 |
4 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 3 2 |
1 2 5 6 9 1 |
|
|
Sample input 2 |
Sample output 2 |
5 1 5 -3 2 6 6 3 34 5 8 10 12 3 18
-25 13 22 11 9
45 23 39 20 15
-49 4 3 |
1 5 -3 6 3 34 10 12 3 13 22 11 |
2-dim
array
Read the
input matrix into a two-dimensional array. Then print the submatrix of size [1 .. r]
× [1 .. c].
Algorithm implementation
Declare a two-dimensional array.
int m[101][101];
Read the input matrix n × n.
scanf("%d", &n);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &m[i][j]);
Read the values of r and c.
scanf("%d %d", &r, &c);
Print the r × c submatrix.
for (i = 1; i <= r; i++)
{
for (j = 1; j <= c; j++)
printf("%d ", m[i][j]);
printf("\n");
}
Java implementation
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();
}
}
Python implementation
Read the input data.
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
r, c = map(int, input().split())
Print the r × c submatrix.
for i in range(r):
for j in range(c):
print(a[i][j],end = " ")
print()
Python implementation – submatrix
Read the input data.
n = int(input())
a = [list(map(int, input().split())) for _ in
range(n)]
r, c = map(int, input().split())
Extract the r × c submatrix
from matrix a.
res = [row[:c] for row in
a[:r]]
Print the r × c submatrix.
for row in res:
print(*row)