美团笔试1--螺旋矩阵
生活随笔
收集整理的這篇文章主要介紹了
美团笔试1--螺旋矩阵
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
螺旋矩陣
輸入兩個整數(shù)n和m,輸出一個n行m列的矩陣,將數(shù)字 1 到 n*m 按照回字蛇形填充至矩陣中。
具體矩陣形式可參考樣例。
輸入格式
輸入共一行,包含兩個整數(shù)n和m。
輸出格式
輸出滿足要求的矩陣。
矩陣占n行,每行包含m個空格隔開的整數(shù)。
數(shù)據(jù)范圍
1≤n,m≤100
輸入樣例:
3 3輸出樣例:
1 2 3 8 9 4 7 6 5定義四個方向
向右 x不變 y+1
向下 x+1 y不變
向左 x不變 y-1
向上 x-1 y不變
撞墻的條件 1 走出邊界
2 走到已經(jīng)被占用的格子
d=(d+1) mod 4
#include <iostream> #include <algorithm>using namespace std;const int N = 110;int n, m; int res[N][N]; bool st[N][N];int main() {cin >> n >> m;int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};int x = 0, y = 0, d = 0;for (int i = 1; i <= n * m; i ++ ){int nx = x + dx[d], ny = y + dy[d];if (nx < 0 || nx >= n || ny < 0 || ny >= m || st[nx][ny]){d = (d + 1) % 4;nx = x + dx[d], ny = y + dy[d];}res[x][y] = i;st[x][y] = true;x = nx, y = ny;}for (int i = 0; i < n; i ++ ){for (int j = 0; j < m; j ++ ) cout << res[i][j] << ' ';cout << endl;}return 0; }
?
轉(zhuǎn)載于:https://www.cnblogs.com/kelly1895/p/10816101.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的美团笔试1--螺旋矩阵的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot集成Apollo分布
- 下一篇: html中的点击事件