碎了没?# Joke - 肚皮舞运动
K*i
1 楼
const int M = 4;
const int N = 5;
// si: row of the upper left element of the sub matrix
// sj: col of the upper left elment of the sub matrix
// m: rows of the current sub matrix
// n: cols of the current sub matrix
void PrintMatrix(int A[M][N], int si, int sj, int m, int n)
{
if (m == 0 || n == 0)
return;
if (m == 1)
{
for (int j = 0; j < n; j++)
cout << A[si + 0][sj + j] << " ";
}
else if (n == 1)
{
for (int i = 0; i < m; i++)
cout << A[si + i][sj + 0] << " ";
}
else
{
for (int j = 0; j < n - 1; j++)
cout << A[si + 0][sj + j] << " ";
for (int i = 0; i < m - 1; i++)
cout << A[si + i][sj + n - 1] << " ";
for (int j = n - 1; j > 0; j--)
cout << A[si + m - 1][sj + j] << " ";
for (int i = m - 1; i > 0; i--)
cout << A[si + i][sj + 0] << " ";
PrintMatrix(A, si + 1, sj + 1, m - 2, n - 2);
}
}
int main()
{
int A[M][N] = { {1, 2, 3, 4, 5}, {5, 6, 7, 8, 9}, {10, 11 ,12, 13,
14}, {15, 16, 17, 18, 19}};
PrintMatrix(A, 0, 0, M, N);
}
const int N = 5;
// si: row of the upper left element of the sub matrix
// sj: col of the upper left elment of the sub matrix
// m: rows of the current sub matrix
// n: cols of the current sub matrix
void PrintMatrix(int A[M][N], int si, int sj, int m, int n)
{
if (m == 0 || n == 0)
return;
if (m == 1)
{
for (int j = 0; j < n; j++)
cout << A[si + 0][sj + j] << " ";
}
else if (n == 1)
{
for (int i = 0; i < m; i++)
cout << A[si + i][sj + 0] << " ";
}
else
{
for (int j = 0; j < n - 1; j++)
cout << A[si + 0][sj + j] << " ";
for (int i = 0; i < m - 1; i++)
cout << A[si + i][sj + n - 1] << " ";
for (int j = n - 1; j > 0; j--)
cout << A[si + m - 1][sj + j] << " ";
for (int i = m - 1; i > 0; i--)
cout << A[si + i][sj + 0] << " ";
PrintMatrix(A, si + 1, sj + 1, m - 2, n - 2);
}
}
int main()
{
int A[M][N] = { {1, 2, 3, 4, 5}, {5, 6, 7, 8, 9}, {10, 11 ,12, 13,
14}, {15, 16, 17, 18, 19}};
PrintMatrix(A, 0, 0, M, N);
}