蛇形矩阵
就是这样的矩阵:
输出矩阵高度和宽度,输出矩阵。
题解:
用 left 指向待输出部分的最左侧,right 指向待输出部分的最右侧,top 指向待输出部分的最上侧,bottom 指向待输出部分的最下侧。
循环指向:
1. 从左到右构造最上侧的一行,待出去部分的最上侧下移,然后top+1。
2. 从上到下构造最右侧的一列,待输出部分的最右侧左移,然后right-1。
3. 从右到左构造最下方的一行,待输出部分的最下侧上移,然后bottom-1。
4. 从下到上构造最右侧的一列。待输出部分的最左侧右移。然后left+1。
直到:left < right && top < bottom
示意图:
代码:
//cpp
#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
int main()
{
int r,c;
cin >> r >> c;
int left = 0, right = c - 1;
int top = 0, bottom = r - 1;
int k = 1;
while(left <= right || top <= bottom)
{
for(int i = left; i <= right && top <= bottom; i++)//构造最上面一行
{
a[top][i] = k++;
}
top++;
for(int i = top; i <= bottom && left <= right; i++)//构造最右侧一列
{
a[i][right] = k++;
}
right--;
for(int i = right; i >= left && top <= bottom; i--)//构造最下面一行
{
a[bottom][i] = k++;
}
bottom--;
for(int i = bottom; i >= top && left <= right; i--)//构造最左侧一列
{
a[i][left] = k++;
}
left++;
}
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++) cout<< a[i][j] << " ";
cout << endl;
}
return 0;
}
觉得不错可以点个赞
这里应该是
while(left <= right && top <= bottom)
吧?直到:left < right && top < bottom停止
这里应该是或者,即while(left <= right || top <= bottom)
我感觉也是
看怎么理解的了,其实都对
没有区别,两个条件是先后满足的,不会发生其中一个条件领先两步的情况,因此||和&&这里没有区别。
妙啊,果然还是模拟法简单好理解
模拟法一般都是比较好想出来,但是代码会比较冗余,时间复杂度一般也比较高
同意 菜鸡模拟了一年还是来看题解了
终于看懂了😭
很强,很有画面感。
很强,比较有画面感
for循环里面的left<=right 跟top<=bottom 的目的是啥啊
left,top,rigth,bottom每次小循环结束都在自增或自减,要确保每次小循环开始前都满足大循环(left <= right &&top <= bottom)的条件。(这题大循环博主写的宽泛了,while(x1<=x2&&y1<=y2)就能过)
你咋代码比我都长咧?
只有后面两个需要判断条件