梦游神


私信TA

用户名:2214999

访问量:5050

签 名:

等  级
排  名 356
经  验 5110
参赛次数 3
文章发表 34
年  龄 0
在职情况 学生
学  校 山东
专  业

  自我简介:

解题思路:

BFS  多加几个判断条件

注意事项:


当时间<2*k,可能原地不动,也可能动。


当时间>=2*k之后,就不用原地不动了,直接走。



参考代码:

#include"bits/stdc++.h"
using namespace std;
char a[1000][1000];
int v[1000][1000];
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
int n;
int k;
int len;
struct node{
	int x;
	int y;
	int step;
};
queue<node> q;
bool check(int xx,int yy,int time){
	if(time<k)
	len=2;
	else if(time>=k&&time<2*k)
	len=1;
	else
	len=0;
	for(int i=xx-len;i<=xx+len;i++){
		for(int j=yy-len;j<=yy+len;j++){
	            if(a[i][j]=='*')
				return false;	 
	  }
    } 
  if(xx<=0||yy<=0||xx>n||yy>n||v[xx][yy]==1||a[xx][yy]=='*')
  return false;
 return true;
}
void bfs(int nx,int ny){
	node pre;
	node next;
	node pree;
	pre.x=nx;
	pre.y=ny;
	pre.step=0;
	v[pre.x][pre.y]=1;
	q.push(pre);
	while(q.size()){
		pre=q.front();
		q.pop();
		
		if(pre.x==n-2&&pre.y==n-2){
			cout<<pre.step;
			return ;
		}
		
		if(pre.step<2*k ){            //原地不动 
		 pree.step=pre.step+1;
		 pree.x=pre.x;
		 pree.y=pre.y;
		 q.push(pree);
		} 
		
		for(int i=0;i<4;i++){                
			next.x=pre.x+dx[i];
			next.y=pre.y+dy[i];
			next.step=pre.step;
			if(check(next.x,next.y,next.step)){    //能动
				v[next.x][next.y]=1;
			 	 next.step=pre.step+1;
				q.push(next);
			}
		}
 	}
}

int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>a[i][j];
		}
	}
	
	bfs(3,3);
	return 0;
}


 

0.0分

6 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区