栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

填数,好像悟了一点!

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

填数,好像悟了一点!

蛇形填数大汇总
    • 问题一
      • 代码
    • 问题二(蓝桥杯s型填数)
      • 代码

问题一

代码
#include  

using namespace std;


int main() {
	int n;
	cin >> n;
	vector>  res(n + 2, vector(n + 2,0));
	int count = 1;
	res[1][n] = 1;
	int x = 1;
	int y = n;
	while(count < n *n) {
		//向下走 
		while(x + 1 <= n && !res[x + 1][y]) {
			res[++x][y] = ++count;
		}
		//向左
		while(y - 1 > 0 && !res[x][y - 1]) {
			res[x][--y] = ++count;
		}
		//向上
		while(x - 1 > 0 && !res[x - 1][y]) {
			res[--x][y] = ++count;
		}
		//向右
		while(y + 1 <= n && !res[x][y + 1]) {
			res[x][++y] = ++count;
		} 
	}
    for(int i = 1; i <= n; i++) {
    	for(int j = 1; j <= n; j++) {
   			if(j != n) {
   				cout << " ";
			} else {
				cout << endl;
			}
		}
	}
	return 0;
}
问题二(蓝桥杯s型填数)


输入:一个数字n
输出:如图所示的上三角(n*n)

代码
#include  

using namespace std;


int main() {
	int n;
	cin >> n;
	vector>  res(n + 2, vector(n + 2,0));
	int count = 1;
	res[1][1] = 1;
	int x = 1;
	int y = 1;
	while(count < n * (n + 1) / 2) {
		y++;	//向左 
		//斜向下走 
		while(x != 0 && y != 0 && !res[x + 1][y - 1]) {
			res[x++][y--] = ++count;
		}
		y++;	//向下
		//斜向上走
		while(x != 0 && y != 0 && !res[x - 1][y + 1]) {
			res[x--][y++] = ++count;
		}
        //跳回到输出的矩阵内,好继续后面的while循环
		x++;
		y--;
	}
    for(int i = 1; i <= n; i++) {
    	for(int j = 1; j <= n - i + 1; j++) {
    		cout << res[i][j];
    		if(j != n - i + 1) {
    			cout << " ";
			} else {
				cout << endl;
			}
		}
	}
	return 0;
}

更多汇总填数问题请移步–>我的语雀

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308648.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号