赞
踩
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
0 1 2 2
- #include<bits/stdc++.h>
- using namespace std;
- int a,b;
- char q[20][20];
- void su(int x,int y)
- {
- int dx,dy;
- q[x][y]='*';//将走过的改为'*'
- for(int i=-1;i<=1;i++)
- {
- for(int j=-1;j<=1;j++)
- {
- dx=x+i;
- dy=y+j;
- if(dx>=0&&dx<a&&dy>=0&&dy<b&&q[dx][dy]=='@')
- su(dx,dy);
- }
- }
- //下面八个if和上面两个for循环效果相同,不过更容易理解一些。
- /*if(x-1>=0&&q[x-1][y]=='@')//向上
- {
- su(x-1,y);
- }
- if(x+1<a&&q[x+1][y]=='@')//向下
- {
- su(x+1,y);
- }
- if(y-1>=0&&q[x][y-1]=='@')//向左
- {
- su(x,y-1);
- }
- if(y+1<b&&q[x][y+1]=='@')//向右
- {
- su(x,y+1);
- }
- if(x-1>=0&&y-1>=0&&q[x-1][y-1]=='@')//左斜向上
- {
- su(x-1,y-1);
- }
- if(x+1<a&&y-1>=0&&q[x+1][y-1]=='@')//左斜向下
- {
- su(x+1,y-1);
- }
- if(y+1<b&&x-1>=0&&q[x-1][y+1]=='@')//右斜向上
- {
- su(x-1,y+1);
- }
- if(y+1<b&&x+1<a&&q[x+1][y+1]=='@')//右斜向下
- {
- su(x+1,y+1);
- }* /
- //return ;利用递归后退,每走到无路可走就后退。
- }
- int main()
- {
- int i,j,sum;
- while(cin>>a>>b,a!=0&&b!=0)
- {
- sum=0;
- for(i=0;i<a;i++)
- {
- for(j=0;j<b;j++)
- {
- cin>>q[i][j];
- }
- }
- for(i=0;i<a;i++)
- {
- for(j=0;j<b;j++)
- {
- if(q[i][j]=='@')
- {
- su(i,j);
- sum++;
- }
- }
- }
- cout<<sum<<endl;
- }
- return 0;
- }
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
- #include<bits/stdc++.h>
- using namespace std;
-
- int x2,y2,num;
- int to[8][2]={1,-2,2,-1,2,1,1,2,-1,2,-2,1,-2,-1,-1,-2};
- int q[10][10];
- char a,b,c,d;
-
- struct place
- {
- int x,y,moves;
- };
- int check(int x,int y)
- {
- if(x<0||y<0||x>7||y>7||q[x][y]==1)
- return 1;
- return 0;
- }
- int bfs()
- {
- place n,m,next;
- queue<place>w;
- memset(q,0,sizeof(q));
- n.x=a-'a';
- n.y=b-'1';
- n.moves=0;
- x2=c-'a';
- y2=d-'1';
- q[n.x][n.y]=1;
- w.push(n);
- while(!w.empty())
- {
- m=w.front();
- w.pop();
- if(m.x==x2&&m.y==y2)
- return m.moves;
- for(int i=0;i<8;i++)
- {
- next.x=m.x+to[i][0];
- next.y=m.y+to[i][1];
- if(next.x==x2&&next.y==y2)
- return m.moves+1;
- if(check(next.x,next.y))
- continue;
- next.moves=m.moves+1;
- q[next.x][next.y]=1;
- w.push(next);
- }
- }
- }
- int main()
- {
- while(scanf("%c%c %c%c",&a,&b,&c,&d)!=EOF)
- {
- getchar();
- num=bfs();
- printf("To get from %c%c to %c%c takes %d knight moves.\n",a,b,c,d,num);
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。