解题思路

这是一道模拟题,要求按顺时针顺序打印矩阵元素。主要思路如下:

  1. 使用四个变量 记录当前需要处理的矩阵边界
  2. 使用 记录当前位置,根据位置判断应该往哪个方向打印
  3. 按照以下顺序打印:
    • 当在左上角时:从左到右打印上边
    • 当在右上角时:从上到下打印右边
    • 当在右下角时:从右到左打印下边
    • 当在左下角时:从下到上打印左边
  4. 每打印完一条边,更新相应的边界和当前位置
  5. 重复直到所有元素都被打印完

代码

#include <iostream>
using namespace std;

const int MAXN = 2010;

int main() {
    int n, m;
    while(cin >> n >> m && ~n && ~m) {
        int a[MAXN][MAXN];
        // 读入矩阵
        for(int i = 1; i <= n; ++i) {
            for(int j = 1; j <= m; ++j) {
                cin >> a[i][j];
            }
        }
        
        // 边界变量
        int lx = 1, rx = n, ly = 1, ry = m;
        // 当前位置
        int x = 1, y = 1;
        // 存储结果
        int ans[MAXN * MAXN], top = 0;
        
        while(lx <= rx && ly <= ry) {
            if(x == lx && y == ly) {  // 左上角
                for(int i = ly; i <= ry; ++i) {
                    ans[++top] = a[lx][i];
                }
                ++lx;
                x = lx;
                y = ry;
            }
            else if(x == lx && y == ry) {  // 右上角
                for(int i = lx; i <= rx; ++i) {
                    ans[++top] = a[i][ry];
                }
                --ry;
                x = rx;
                y = ry;
            }
            else if(x == rx && y == ry) {  // 右下角
                for(int i = ry; i >= ly; --i) {
                    ans[++top] = a[rx][i];
                }
                --rx;
                x = rx;
                y = ly;
            }
            else if(x == rx && y == ly) {  // 左下角
                for(int i = rx; i >= lx; --i) {
                    ans[++top] = a[i][ly];
                }
                ++ly;
                x = lx;
                y = ly;
            }
        }
        
        // 输出结果
        for(int i = 1; i <= top; ++i) {
            cout << ans[i];
            if(i < top) cout << ",";
        }
        cout << endl;
    }
    return 0;
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        while(true) {
            String[] s = br.readLine().split(" ");
            int m = Integer.parseInt(s[0]);
            int n = Integer.parseInt(s[1]);
            if(m < 0) break;
            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++) {
                String[] temp = br.readLine().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(temp[j]);
            }
            print(matrix, m-1, n-1);
        }
    }
    public static void print(int[][] nums, int rows, int cols){
        int r=0, c=0;
        StringBuilder sb = new StringBuilder();
        while (r<rows && c<cols){
            for(int i=c; i<=cols; i++){
                sb.append(nums[r][i]).append(',');
            }
            for(int i=r+1; i<=rows; i++){
                sb.append(nums[i][cols]).append(',');
            }
            for(int i=cols-1; i>=c;i--){
                sb.append(nums[rows][i]).append(',');
            }
            for (int i=rows-1; i>r;i--){
                sb.append(nums[i][c]).append(',');
            }
            r++;
            rows--;
            c++;
            cols--;
        }

        if(r==rows){
            for(int i =c;i<=cols;i++){
                sb.append(nums[rows][i]).append(',');
            }
        }else if(c==cols){
            for(int i=r; i<=rows; i++){
                sb.append(nums[i][cols]).append(',');
            }
        }
        System.out.println(sb.substring(0,sb.length()-1));

    }
}

while True:
    try:
        n, m = map(int, input().split())
        if n == -1 and m == -1:
            break
            
        # 读入矩阵
        a = [[0] * (m + 1) for _ in range(n + 1)]
        for i in range(1, n + 1):
            row = list(map(int, input().split()))
            for j in range(1, m + 1):
                a[i][j] = row[j-1]
        
        # 边界变量
        lx, rx = 1, n
        ly, ry = 1, m
        # 当前位置
        x, y = 1, 1
        # 存储结果
        ans = []
        
        while lx <= rx and ly <= ry:
            if x == lx and y == ly:  # 左上角
                for i in range(ly, ry + 1):
                    ans.append(a[lx][i])
                lx += 1
                x = lx
                y = ry
            elif x == lx and y == ry:  # 右上角
                for i in range(lx, rx + 1):
                    ans.append(a[i][ry])
                ry -= 1
                x = rx
                y = ry
            elif x == rx and y == ry:  # 右下角
                for i in range(ry, ly - 1, -1):
                    ans.append(a[rx][i])
                rx -= 1
                x = rx
                y = ly
            elif x == rx and y == ly:  # 左下角
                for i in range(rx, lx - 1, -1):
                    ans.append(a[i][ly])
                ly += 1
                x = lx
                y = ly
        
        # 输出结果
        print(','.join(map(str, ans)))
        
    except EOFError:
        break

算法及复杂度

  • 算法:模拟
  • 时间复杂度: - 需要访问矩阵中的每个元素一次
  • 空间复杂度: - 需要存储输入矩阵和结果数组