将矩阵按对角线排序(c++题解)

题目描述

矩阵对角线 是一条从矩阵最上面行或者最左侧列中的某个元素开始的对角线,沿右下方向一直到矩阵末尾的元素。例如,矩阵 mat 有 6 行 3 列,从 mat[2][0] 开始的 矩阵对角线 将会经过 mat[2][0]、mat[3][1] 和 mat[4][2] 。

给你一个 m * n 的整数矩阵 mat ,请你将同一条 矩阵对角线 上的元素按升序排序后,返回排好序的矩阵。

输入格式

第一行输入两个整数m和n

接下来输入一个 m * n 的整数矩阵 mat

输出格式

输出排好序的矩阵

样例

样例输入 1

复制代码
复制3 4
3 3 1 1
2 2 1 2
1 1 1 2

样例输出 1

复制代码
复制1 1 1 1
1 2 2 2
1 2 3 3

样例输入 2

复制代码
复制5 6
11 25 66 1 69 7
23 55 17 45 15 52
75 31 36 44 58 8
22 27 33 25 68 4
84 28 14 11 5 50

样例输出 2

复制代码
复制5 17 4 1 52 7
11 11 25 45 8 69
14 23 25 44 58 15
22 27 31 36 50 66
84 28 75 33 55 68

数据范围与提示

m == mat.length

n == mat[i].length

1 <= m, n <= 100

1 <= mat[i][j] <= 100


日常发作业题解。

总结就是斜着冒泡

也是简单到爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆爆表的题

写作不易,点个赞呗!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int a[10005][10005];
int n,m;
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>a[i][j];
		}
	}
	for(int i=n;i>=1;i--){
		int flag=false;
		while(flag==false){
			flag=true;
			int x=i,y=1;
			while(x<n&&y<m){
				x++,y++;
				if(a[x-1][y-1]>a[x][y])
				swap(a[x-1][y-1],a[x][y]),flag=false;
			}
		}
	}
	for(int i=2;i<=m;i++){
		int flag=false;
		while(flag==false){
			flag=true;
			int x=1,y=i;
			while(x<n&&y<m){
				x++,y++;
				if(a[x-1][y-1]>a[x][y])
				swap(a[x-1][y-1],a[x][y]),flag=false;
			}
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cout<<a[i][j]<<" ";
		}
		cout<<endl;
	}
}
相关推荐
铉铉这波能秀6 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马6 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
唐梓航-求职中6 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹6 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll13045252986 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
林开落L6 小时前
从零开始学习Protobuf(C++实战版)
开发语言·c++·学习·protobuffer·结构化数据序列化机制
Physicist in Geophy.6 小时前
从矩阵到函数(算子理论)
矩阵·math
林开落L6 小时前
从入门到了解:Protobuf、JSON、XML 核心解析(C++ 示例)
xml·c++·json·protobuffer·结构化数据序列化机制
Queenie_Charlie7 小时前
stars(树状数组)
数据结构·c++·树状数组
颜酱7 小时前
二叉树遍历思维实战
javascript·后端·算法