zoukankan      html  css  js  c++  java
  • SPOJ SERGRID 【BFS】

    思路:
    在一个方向上走K步,基础BFS。
    注意标记;
    注意路径;

    PS:显著注释是记录路径。

    #include<bits/stdc++.h>
    using namespace std;
    
    const int N=5e2+10;
    char ma[N][N];
    bool vis[N][N];
    int dx[4]={0,0,-1,1};
    int dy[4]={1,-1,0,0};
    /***************/
    //int prex[N][N];
    //int prey[N][N];
    /***************/
    
    struct asd{
    	int x,y;
    	int step;
    };
    int n,m;
    
    int BFS()
    {
    	asd now,nex;
    	queue<asd>q;
    	memset(vis,false,sizeof(vis));
    	now.x=0;
    	now.y=0;
    	now.step=0;
    	/********************/
    	//prex[0][0]=-1;
    	//prey[0][0]=-1;
    	/********************/
    	vis[0][0]=true;
    	q.push(now);
    	while(!q.empty())
    	{
    		now=q.front();q.pop();
    		int st=ma[now.x][now.y]-'0';
    		if(now.x==n-1&&now.y==m-1)
    			return now.step;
    		for(int i=0;i<4;i++)
    		{
    			int x=now.x+dx[i]*st;
    			int y=now.y+dy[i]*st;
    			if(x<0||y<0||x>=n||y>=m||vis[x][y]||(x==now.x&&y==now.y))
    				continue;
    			nex.x=x;
    			nex.y=y;
    			/******************/
    			//prex[x][y]=now.x;
    			//prey[x][y]=now.y;
    			/******************/
    			vis[x][y]=true;
    			nex.step=now.step+1;
    			q.push(nex);
    		}
    	}
    	return -1;
    }
    
    int main()
    {
    	scanf("%d%d",&n,&m);
    	for(int i=0;i<n;i++)
    		scanf("%s",ma[i]);
    	printf("%d
    ",BFS());
    	/*****************/
    	//int x=n-1,xx;
    	//int y=m-1,yy;
    	//while(x!=-1&&y!=-1)
    	//{
    	//	printf("%d %d
    ",x,y);
    	//	xx=prex[x][y];
    	//	yy=prey[x][y];
    	//	x=xx;y=yy;
    	//}
    	/******************/
    	return 0;
    }
    


  • 相关阅读:
    数字证书学习笔记
    在微服务中使用领域事件
    用Gradle构建Spring Boot项目
    七言 朱雀
    作为分享者
    Spring Framework学习要点摘抄
    Servlet 3.0/3.1 中的异步处理
    Java集合学习笔记
    Java垃圾回收学习笔记
    你究竟有多了解Spring?
  • 原文地址:https://www.cnblogs.com/keyboarder-zsq/p/6777383.html
Copyright © 2011-2022 走看看