給定一個n行m列的二維數組,左上角為1,蛇形遞增,輸出最後的數組
1 2 3
8 9 4
7 6 5
代碼1(自己寫的):
兩種方法均借鑒了wrong的思路,wrong的代碼中第二種方法隻寫了思路沒有調試,是以出現了資料被覆寫,自己的代碼完善了wrong寫的第二種簡易方法。
#include <iostream>
#include <stdio.h>
const int maxn = 100;
using namespace std;
int snake[maxn][maxn];
int n,m;
bool boundary(int r,int c)
{
if(r<1 || r>n || c<1 || c>m)
return 0;
else
return 1;
}
int main()
{
int r = 1;int c = 1;
int cot = 1;
scanf("%d%d",&n,&m);
int d = 0; //控制方向0、1、2、3
int dir[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
while(cot<=n*m)
{
//方法一
/* while(cot<=n*m)
{
snake[r][c] = cot;
c++;
cot++;
if(!boundary(n,m) || snake[r][c])
{
r++;
c--;
break;
}
}
while(cot<=n*m)
{
snake[r][c] = cot;
r++;
cot++;
if(!boundary(n,m) || snake[r][c])
{
r--;
c--;
break;
}
}
while(cot<=n*m)
{
snake[r][c] = cot;
c--;
cot++;
if(!boundary(n,m) || snake[r][c])
{
r--;
c++;
break;
}
}
while(cot<=n*m)
{
snake[r][c] = cot;
r--;
cot++;
if(!boundary(n,m) || snake[r][c])
{
r++;
c++;
break;
}
}
*/
//方法二
while(cot<=n*m)
{
snake[r][c] = cot++;
r+=dir[d][0]; //控制行坐标
c+=dir[d][1]; //控制列坐标
if(!boundary(r,c) || snake[r][c])
{
r-=dir[d][0]; //以下兩行為越界調整
c-=dir[d][1];
d++; //以下四行為提前調整到下一個位置
d%=4;
r+=dir[d][0];
c+=dir[d][1];
break;
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%4d",snake[i][j]);
printf("\n");
}
return 0;
}
代碼2(西交wrong):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
const int maxn = 105;
typedef pair<int,int> P;
int mp[maxn][maxn]; //記錄輸出的值
int n,m;
bool in_bound(int r,int c)//判斷目前(r,c)是否合法
{
if(r>n||r<1||c>m||c<1) return false;
return true;
}
int main()
{
int cot=1,r=1,c=1; //目前處于r行c列
cin>>n>>m;
memset(mp,0,sizeof(mp));//mp數組清零
/*方法一
while(cot<=n*m)
{
while(cot<=n*m)
{
mp[r][c]=cot;
cot++;
c++;
if(!in_bound(r,c)||mp[r][c]) break;
} //已經不能再向右行走
c--;
r++;
while(cot<=n*m)
{
mp[r][c]=cot;
cot++;
r++;
if(!in_bound(r,c)||mp[r][c]) break;
} //已經不能再向下行走
r--;
c--;
while(cot<=n*m){
mp[r][c]=cot;
cot++;
c--;
if(!in_bound(r,c)||mp[r][c]) break;
} //已經不能再向左行走
c++;
r--;
while(cot<=n*m){
mp[r][c]=cot;
cot++;
r--;
if(!in_bound(r,c)||mp[r][c]) break;
} //已經不能再向上行走
r++;
c++;
}
*/
//方法二
int d=0;//0 1 2 3
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
while(cot<=n*m)
{
d%=4;
while(cot<=n*m)
{
mp[r][c]=cot++;
r+=dir[d][0];c+=dir[d][1];
if(!in_bound(r,c)||mp[r][c]) {r-=dir[d][0];c-=dir[d][1];d++;break;}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%4d",mp[i][j]);
cout<<endl;
}
return 0;
}
(感謝西交wrong學長提供以上題目練習)