题目:
对于一个 nn 行 mm 列的表格,我们可以使用螺旋的方式给表格依次填上正整数,我们称填好的表格为一个螺旋矩阵。
例如,一个 4 行 5 列的螺旋矩阵如下:
1 2 3 4 5
14 15 16 17 6
13 20 19 18 7
12 11 10 9 8
输入描述
输入格式:
输入的第一行包含两个整数 n, mn,m,分别表示螺旋矩阵的行数和列数。
第二行包含两个整数 r, cr,c,表示要求的行号和列号。
其中,2 \leq n, m \leq 1000,1 \leq r \leq n,1 \leq c \leq m2≤n,m≤1000,1≤r≤n,1≤c≤m。
输出描述
输出一个整数,表示螺旋矩阵中第 rr 行第 cc 列的元素的值。
#include <iostream>
using namespace std;
int main(){
//n行 m列
int n,m,r,c,i=1;
cin>>n>>m>>r>>c;
int count=0;
int arr[n][m];
int s[n][m]={0};
int x=0,y=0;
while(count<m*n)
{
while(s[x][y+1]==0&&y+1<m) //向右遍历
{
arr[x][y]=i;
i++;
y++;
s[x][y]=1;
count++;
}
while(s[x+1][y]==0&&x+1<n) //向下遍历
{
arr[x][y]=i;
i++;
x++;
s[x][y]=1;
count++;
}
while(s[x][y-1]==0&&y-1>=0) //向左遍历
{
arr[x][y]=i;
i++;
y--;
s[x][y]=1;
count++;
}
while(s[x-1][y]==0&&x-1>=0) //向上遍历
{
arr[x][y]=i;
i++;
x--;
s[x][y]=1;
count++;
}
}
cout<<arr[r-1][c-1];
return 0;
}
检查了好几遍感觉写得没有问题
为什么输出不了数据呢?
麻烦各位帮忙看看!谢谢!!
你把数组输出出来看看数组正确不,数组不正确结果也不对呀
#include <iostream>
using namespace std;
int main()
{
// n行 m列
int n, m, r, c, i = 1;
cin >> n >> m >> r >> c;
// int count = 0;
// int arr[n][m] = {0};
// int s[n][m] = {0};
int **arr = new int *[n];
for (int i = 0; i < n; i++)
arr[i] = new int[m];
int **s = new int *[n];
for (int i = 0; i < n; i++)
s[i] = new int[m]{0};
int x = 0, y = 0;
int tn = n, tm = m, tx = 0, ty = 0;
while (i <= m * n)
{
x = tx;
y = ty;
while (y + 1 < m && s[x][y + 1] == 0) //向右遍历
{
arr[x][y] = i;
i++;
y++;
s[x][y] = 1;
// count++;
}
while (x + 1 < n && s[x + 1][y] == 0) //向下遍历
{
arr[x][y] = i;
i++;
x++;
s[x][y] = 1;
// count++;
}
while (y - 1 >= 0 && s[x][y - 1] == 0) //向左遍历
{
arr[x][y] = i;
i++;
y--;
s[x][y] = 1;
// count++;
}
while (x - 1 >= 0 && s[x - 1][y] == 0) //向上遍历
{
arr[x][y] = i;
i++;
x--;
s[x][y] = 1;
// count++;
}
tx++;
ty++;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << arr[i][j] << "\t";
cout << endl;
}
cout << endl;
cout << arr[r - 1][c - 1] << endl;
return 0;
}