第一题:“消消乐“
解决思路:
代码实现:(这里我用的递归(栈)实现的,BSF方法见书P278)
#include<bits/stdc++.h>
using namespace std;
int m,n,ans=0;
int a[20][20]={0};
bool b[20][20]={0};
int nx[4]={0,0,1,-1};
int ny[4]={1,-1,0,0};
bool judge(int x1,int y1)
{
if(x1<0||x1>m||y1<0||y1>n)
return false;
if(a[x1][y1]==0||b[x1][y1]==1)
return false;
else
{
return 1;
}
}
void boom(int x,int y)
{
b[x][y]=1; //标记已访问过
int i,j;
for(i=0;i<4;i++)
{
int newx=x+nx[i];
int newy=y+ny[i];
if(judge(newx,newy))
{
boom(newx,newy);
}
}
}
int main()
{
int i=0,j=0;
cin>>m>>n;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(b[i][j]==0&&a[i][j]==1)
{
ans++;
boom(i,j);
}
}
}
cout<<ans<<endl;
system("pause");
}
案例输入:
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
输出:11
第二题:迷宫
代码实现:
#include <bits/stdc++.h>
using namespace std;
int ans=0;
int m,n;
//int startx,starty,endx,endy,nowx,nowy;
const int maxn=20;
char maze[maxn][maxn];
int flag[maxn][maxn]={0};
int nx[4]={0,0,1,-1};
int ny[4]={1,-1,0,0};
struct node
{
int x,y;
int step;
}S,T,Node; //起点、终点、临时点
bool test(int x,int y)
{
if(x<0||x>=m||y<0||y>=n)return false;
if(maze[x][y]=='*')return false;
if(flag[x][y]==1)return false;
return true;
}
int BFS()
{
queue<node> q;
q.push(S); //起点入队
while(!q.empty())
{
node top = q.front();
q.pop();
if(top.x==T.x && top.y==T.y)
return top.step;
int i;
for(i=0;i<4;i++)
{
int newx=top.x+nx[i];
int newy=top.y+ny[i];
if(test(newx,newy))
{
Node.x=newx;
Node.y=newy;
Node.step=top.step+1;
q.push(Node);
flag[newx][newy]=1;
}
}
}
return -1;
}
int main()
{
cin>>m>>n;
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>maze[i][j];
if(maze[i][j]=='S')
{
S.x=i;
S.y=j;
S.step=0;
}
else if(maze[i][j]=='T')
{
T.x=i;
T.y=j;
}
}
}
ans=BFS();
cout<<ans<<endl;
system("pause");
return 0;
}
案例输入:
5 5
. . . . .
. * . * .
. * S * .
. * * * .
. . . T *
输出:11