WA了一次,最后發現竟然是多次計算時沒給result賦初值,改了以后就AC了~
題目是寫一個超簡化版的貪吃蛇,在50*50的矩陣中,起始位置是蛇頭位于的(25,30),蛇尾在(25,11),蛇占20個格。蛇可以向E W N S四個方向移動,當然不能反向移動,也不能撞倒自己或者撞倒墻.
輸入多組case,每組是一串字符,表示每次的移動方向.
輸出是否能完成這些移動,如果不能,就判斷是在第幾次移動時撞倒自己還是墻.
我的思路是 在矩陣中,將蛇占據的位置用1標記,將蛇頭到蛇尾的20個坐標存入一個vector,然后每次移動,先判斷是否撞倒墻,如果沒撞倒墻,就先將蛇尾刪除,將舊蛇頭的位置置0(新蛇頭可以是舊蛇尾 ),再將新的蛇頭存入vector,判斷新的蛇頭所在的位置是否為0,若為被占據,則置1,繼續移動.
覺得自己寫得很冗余,開始時只記錄了蛇頭和蛇尾的坐標,以為根據蛇頭移動就可以判斷蛇尾的移動,寫著寫著就發現問題了,臨時加了個vector來存蛇的坐標,所以程序有點亂,也只有這樣了,以后再改改吧~
我的AC代碼:
1
#include<iostream>
2
#include<vector>
3
#include<string>
4
using namespace std;
5
struct point
6
{
7
int row;
8
int col;
9
};
10
int main()
11
{
12
int i,j,n,index,result=1;
13
string moves;
14
char move;
15
point p;
16
vector<point>v;
17
while(1)
18
{
19
result=1;
20
cin>>n;
21
if(n==0)break;
22
23
int s[50][50]={0};
24
int fristr=24,fristc=29,lastr=24,lastc=10;
25
cin>>moves;
26
for(j=10;j<30;j++)
27
{
28
s[24][j]=1;
29
p.row=24;
30
p.col=j;
31
v.push_back(p);
32
}
33
for(index=0;index<n;index++)
34
{
35
move=moves[index];
36
if(move=='E')++fristc;
37
if(move=='W')--fristc;
38
if(move=='N')--fristr;
39
if(move=='S')++fristr;
40
if(fristr*(fristr-49)>0||fristc*(fristc-49)>0)
41
{
42
cout<<"The worm ran off the board on move "<<index+1<<"."<<endl;
43
result=0;
44
break;
45
}
46
v.erase(v.begin());
47
p.row=fristr;
48
p.col=fristc;
49
v.push_back(p);
50
s[lastr][lastc]=0;
51
lastr=v[0].row;
52
lastc=v[0].col;
53
if(s[fristr][fristc])
54
{
55
cout<<"The worm ran into itself on move "<<index+1<<"."<<endl;
56
result=0;
57
break;
58
}
59
s[fristr][fristc]=1;
60
}
61
if(result)printf("The worm successfully made all %d moves.\n", n);
62
v.clear();
63
getchar()
64
}
65
}
66
#include<iostream>2
#include<vector>3
#include<string>4
using namespace std;5
struct point6
{7
int row;8
int col;9
};10
int main()11
{12
int i,j,n,index,result=1;13
string moves;14
char move;15
point p;16
vector<point>v;17
while(1)18
{19
result=1;20
cin>>n;21
if(n==0)break;22

23
int s[50][50]={0};24
int fristr=24,fristc=29,lastr=24,lastc=10;25
cin>>moves;26
for(j=10;j<30;j++)27
{28
s[24][j]=1;29
p.row=24;30
p.col=j;31
v.push_back(p);32
}33
for(index=0;index<n;index++)34
{35
move=moves[index];36
if(move=='E')++fristc;37
if(move=='W')--fristc;38
if(move=='N')--fristr;39
if(move=='S')++fristr;40
if(fristr*(fristr-49)>0||fristc*(fristc-49)>0)41
{42
cout<<"The worm ran off the board on move "<<index+1<<"."<<endl;43
result=0;44
break;45
}46
v.erase(v.begin());47
p.row=fristr;48
p.col=fristc;49
v.push_back(p);50
s[lastr][lastc]=0;51
lastr=v[0].row;52
lastc=v[0].col;53
if(s[fristr][fristc])54
{55
cout<<"The worm ran into itself on move "<<index+1<<"."<<endl;56
result=0;57
break;58
}59
s[fristr][fristc]=1;60
}61
if(result)printf("The worm successfully made all %d moves.\n", n);62
v.clear();63
getchar()64
}65
}66



