回形数

问题描述
  对于一个 n 行 m 列的表格,我们可以使用螺旋的方式给表格依次填上正整数,我们称填好的表格为一个螺旋矩阵。
  例如,一个 4 行 5 列的螺旋矩阵如下:
  1 2 3 4 5
  14 15 16 17 6
  13 20 19 18 7
  12 11 10 9 8
  输入格式
  输入的第一行包含两个整数 n, m,分别表示螺旋矩阵的行数和列数。
  第二行包含两个整数 r, c,表示要求的行号和列号。
输出格式
  输出一个整数,表示螺旋矩阵中第 r 行第 c 列的元素的值。
样例输入
4 5
2 2
样例输出
15

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string.h>
#include<memory.h>
using namespace std;
int a[1000][1000]={(0,0)};

int main()
{
	
	int n,m,r,c;
	cin>>n>>m;
	cin>>r>>c;
	int total=0;
	int p=1; 
	
	int i=0,j=0;
	
	
	
	
	while(total<m*n)//n行  m列 
	{
		
		while(j<=m-1&&a[i][j]==0) //向右 
		{
			a[i][j] = p;
			
			p++;
			j++;
			total++;
		}
		i++;
		j--;//减去多加的
		while(i<=n-1&&a[i][j]==0)//向下 
		{
			a[i][j] = p;
			
			p++;
			i++;
			total++;
		}
		j--;
		i--;
		while(j>=0&&a[i][j]==0)//向左 
		{
			a[i][j] = p;
		
			p++;
			j--;
			total++;
		}
		i--;
		j++;
			while(i>=0&&a[i][j]==0)//向上 
		{
			a[i][j] = p;
		    
			p++;
			i--;
			total++;
		}
		j++;
		i++; 
		
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
			cout<<a[i][j]<<" ";
			cout<<endl;
	}
		
	cout<<a[r-1][c-1]<<endl;
		
	
	return 0;
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
蓝桥杯是中国最具影响力的计算机竞赛之一,形取数是蓝桥杯中的一道经典题目。下面是关于Python实现形取数的介绍: 形取数是指从一个矩阵中按照形的方式依次取出所有的元素。具体来说,就是从矩阵的左上角开始,按照顺时针的方向依次取出元素,直到取完所有元素为止。 在Python中,可以通过嵌套列表来表示矩阵。下面是一个示例代码,实现了形取数的功能: ```python def spiral_order(matrix): if not matrix: return [] rows, cols = len(matrix), len(matrix[0]) top, bottom, left, right = 0, rows - 1, 0, cols - 1 result = [] while top <= bottom and left <= right: # 从左到右 for col in range(left, right + 1): result.append(matrix[top][col]) top += 1 # 从上到下 for row in range(top, bottom + 1): result.append(matrix[row][right]) right -= 1 if top <= bottom: # 从右到左 for col in range(right, left - 1, -1): result.append(matrix[bottom][col]) bottom -= 1 if left <= right: # 从下到上 for row in range(bottom, top - 1, -1): result.append(matrix[row][left]) left += 1 return result # 测试 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = spiral_order(matrix) print(result) ``` 以上代码中,`spiral_order`函数接受一个二维列表作为输入,表示矩阵。函数通过设定上下左右四个边界来控制取数的范围,然后按照顺时针的方向依次取出元素,并将其添加到结果列表中。最后返结果列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值