标签:show queue mes discuss iostream span turn 左右 getc
给定一个N*M方格的迷宫,迷宫里有T处障碍,障碍处不可通过。给定起点坐标和终点坐标,问: 每个方格最多经过1次,有多少种从起点坐标到终点坐标的方案。在迷宫中移动有上下左右四种方式,每次只能移动一个方格。数据保证起点上没有障碍。
无
第一行N、M和T,N为行,M为列,T为障碍总数。第二行起点坐标SX,SY,终点坐标FX,FY。接下来T行,每行为障碍点的坐标。
给定起点坐标和终点坐标,问每个方格最多经过1次,从起点坐标到终点坐标的方案总数。
2 2 1 1 1 2 2 1 2
1
【数据规模】
1≤N,M≤5
对于这一题,我是因为这个才写。
好了,切入正题。
对于这一题,明显要用到搜索算法,那么DFS上场。 对于每一次移动,要判断边界。 此外,终点是否有障碍物也要注意,否则,就会这样。
那么,代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
int sx,sy,ex,ey,ans,n,m,t;
int ma[15][15];//地图
int dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1};//存储上下左右
bool vis[15][15];//记录走过的标记
int read(){//快读
int a=0,b=1;
char ch=getchar();
while((ch<‘0‘||ch>‘9‘)&&(ch!=‘-‘)){
ch=getchar();
}
if(ch==‘-‘){
b=-1;
ch=getchar();
}
while(ch>=‘0‘&&ch<=‘9‘){
a=a*10+ch-‘0‘;
ch=getchar();
}
return a*b;
}
void dfs(int x,int y){
if(x==ex&&y==ey){
ans++;
return ;
}
if((ma[x][y]==-1)||(vis[x][y])||(x<1)||(x>n)||(y<1)||(y>m)){//特判边界是否合法
return;
}
for(int i=1;i<=4;i++){
vis[x][y]=1;
dfs(x+dx[i],y+dy[i]);
vis[x][y]=0;
}
}
int main(){
scanf("%d %d %d",&n,&m,&t);
scanf("%d %d %d %d",&sx,&sy,&ex,&ey);
for(int i=1;i<=t;i++){
int x,y;
scanf("%d%d",&x,&y);
ma[x][y]=-1;
vis[x][y]=1;
if(ex==x&&ey==y){//特判终点有无障碍物
printf("0");
return 0;
}
}
dfs(sx,sy);//DFS跑一次
printf("%d",ans);
return 0;
}
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
int sx,sy,ex,ey,ans,n,m,t;
int ma[15][15];
int dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1};
bool vis[15][15];
int read(){
int a=0,b=1;
char ch=getchar();
while((ch<‘0‘||ch>‘9‘)&&(ch!=‘-‘)){
ch=getchar();
}
if(ch==‘-‘){
b=-1;
ch=getchar();
}
while(ch>=‘0‘&&ch<=‘9‘){
a=a*10+ch-‘0‘;
ch=getchar();
}
return a*b;
}
void dfs(int x,int y){
if(x==ex&&y==ey){
ans++;
return ;
}
if((ma[x][y]==-1)||(vis[x][y])||(x<1)||(x>n)||(y<1)||(y>m)){
return;
}
for(int i=1;i<=4;i++){
vis[x][y]=1;
dfs(x+dx[i],y+dy[i]);
vis[x][y]=0;
}
}
int main(){
scanf("%d %d %d",&n,&m,&t);
scanf("%d %d %d %d",&sx,&sy,&ex,&ey);
for(int i=1;i<=t;i++){
int x,y;
scanf("%d%d",&x,&y);
ma[x][y]=-1;
vis[x][y]=1;
if(ex==x&&ey==y){
printf("0");
return 0;
}
}
dfs(sx,sy);
printf("%d",ans);
return 0;
}
标签:show queue mes discuss iostream span turn 左右 getc
原文地址:https://www.cnblogs.com/xiongchongwen/p/11846211.html