题解 | #矩阵交换#

矩阵交换

http://www.nowcoder.com/practice/ec44d4ff8c794b2f9205bdddbde96817

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[][] arr = new int[n][m];

        int[] c = new int[n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = sc.nextInt();
            }
        }
        // 变换几次
        int k = sc.nextInt();
        // 这里多加一个获取空格
        String ss = sc.nextLine();
        for (int i = 0; i < k; i++) {
            String s = sc.nextLine();
            String t = s.split(" ")[0]; // 操作
            int a =  Integer.valueOf(s.split(" ")[1]); // 行或者列
            int b =  Integer.valueOf(s.split(" ")[2]); // 行或者列
            if (t.equals("r")) {
                // 行变换
                // 创建一个和二维列相同的一维数组
                int[] tmp = new int[m];
                // 将a放到b中
                tmp = arr[a - 1];
                arr[a - 1] = arr[b - 1];
                arr[b - 1] = tmp;
            } else if (t.equals("c")) {
                // 列变换
                // 创建一个和二维行相同的一维数组
                int[] tmp = new int[n];
                // 备份
                for(int j=0; j<arr.length; j++) {
                    tmp[j] = arr[j][a-1];
                }
                // 赋值给a-1列
                  for(int j=0; j<arr.length; j++) {
                    arr[j][a-1] = arr[j][b-1];
                }
                // 赋值给b-1列
                for(int j=0; j<arr.length; j++) {
                    arr[j][b-1] = tmp[j];
                }
            }
        }
        // 输出结果
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
全部评论

相关推荐

05-16 11:16
已编辑
东华理工大学 Java
牛客73769814...:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
牛客创作赏金赛
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务