zoukankan      html  css  js  c++  java
  • UVA 1600 Patrol Robot

    题意::给一个m行n列的矩阵每个小格里面有1和0两种状态,0代表路,1代表障碍,有一个机器人想从(1,1)-->(m,n),最少需要多少步,机器人也可以在障碍里面行走,但是最多只能连续走k个有障碍的格子。

    思路:开三维数组记录坐标和经过的障碍物的个数 数组值为走的步数

    DFS

    #include<bits/stdc++.h>
    using namespace std;
    const int inf=0x3f3f3f3f;
    int mp[25][25];
    int vis[25][25][25];
    int vctorx[4]={1,0,-1,0};
    int vctory[4]={0,1,0,-1};
    int n,m,k;
    
    int dfs(int x,int y,int step,int cnt)
    {
    	if(x==n && y==m) return step;
    	
    	int ans=inf;
    	for(int i=0;i<4;i++)
    	{
    		int nextx=x+vctorx[i];
    		int nexty=y+vctory[i];
    		int top=cnt;
    		if(mp[nextx][nexty]==1) top++;
    		else top=0;
    		
    		if(nextx>=1 && nextx<=n && nexty>=1 && nexty<=m)
    		{
    			if((vis[nextx][nexty][top]==0 || vis[nextx][nexty][top]>step+1) && top<=k)
    			{
    				vis[nextx][nexty][top]=step+1;
    				ans=min(ans,dfs(nextx,nexty,step+1,top));
    			}
    		}
    	}
    	return ans;
    	
    }
    
    int main()
    {
    	int t;
    	cin>>t;
    	while(t--)
    	{		
    		cin>>n>>m;
    		cin>>k;
    		for(int i=1;i<=n;i++)
    		{
    			for(int j=1;j<=m;j++)
    			{
    				cin>>mp[i][j];
    			}
    		}
    		memset(vis,0,sizeof(vis));
    		
    		int ans=dfs(1,1,0,0);
    		if(ans==inf) cout<<"-1"<<endl;
    		else cout<<ans<<endl;
    	}
    	
    	return 0;
     } 
    

    BFS

    #include<bits/stdc++.h>
    using namespace std;
    
    int mp[25][25];
    int vis[25][25][25];
    int dx[4]={1,0,0,-1};
    int dy[4]={0,1,-1,0};
    int n,m,k;
    
    typedef struct node{
    	int x,y,top,step;
    }str;
    
    int bfs()
    {
    	memset(vis,0,sizeof(vis));
    	queue<str> q;
    	str now,next;
    	now.x=now.y=1;
    	now.top=now.step=0;
    	q.push(now);
    	while(!q.empty())
    	{
    		now=q.front();
    		q.pop();
    		if(now.x==n && now.y==m) return now.step;
    		for(int i=0;i<4;i++)
    		{
    			next.x=now.x+dx[i];
    			next.y=now.y+dy[i];
    			next.top=now.top;
    			if(next.x>=1 && next.x<=n && next.y>=1 &&next.y<=m)
    			{
    				if(mp[next.x][next.y]) next.top++;
    				else next.top=0;
    				if(!vis[next.x][next.y][next.top] && next.top<=k)//vis标记是否经过这个位置
    				{
    					next.step=now.step+1;
    					vis[next.x][next.y][next.top]=1;
    					q.push(next);
    				}
    			}	
    		}
    	}
    	return -1;
    }
    
    int main()
    {
    	int t;
    	cin>>t;
    	while(t--)
    	{
    		cin>>n>>m;
    		cin>>k;
    		for(int i=1;i<=n;i++)
    		{
    			for(int j=1;j<=m;j++)
    			{
    				cin>>mp[i][j];
    			}
    		}
    		cout<<bfs()<<endl;
    	}
    	return 0;
     } 
    
  • 相关阅读:
    随感
    createDocumentFragment() 创建文档碎片节点
    关于数组的map、reduce、filter
    CSS中的常用属性
    精通CSS version2笔记2.小知识
    精通CSS version2笔记之⒈选择器
    Spring入门_01
    Spring入门
    Java 流程控制
    Java 数据类型
  • 原文地址:https://www.cnblogs.com/tianming1/p/13714546.html
Copyright © 2011-2022 走看看