HDU 2612 Find a way (bfs)

本文深入探讨了C++在游戏开发领域的应用,从基础语法、内存管理到高级特性如模板、STL容器等进行了详细解析。通过实践案例,读者将学会如何使用C++高效地创建游戏逻辑、优化性能并实现复杂的游戏功能。

简单题,,,

#include "string"
#include "iostream"
#include "cstdio"
#include "cmath"
#include "set"
#include "queue"
#include "vector"
#include "cctype"
#include "sstream"
#include "cstdlib"
#include "cstring"
#include "stack"
#include "ctime"
#include "algorithm"
#define pa pair<int,int>
#define Pi M_PI
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
using namespace std;
typedef long long LL;
#define INF 2<<20
const int M=55;

char mp[205][205];
int dir[4][2]={1,0,-1,0,0,-1,0,1};
int vis[205][205];
int res[201][201];
int n,m;

struct node
{
    int x;
    int y;
    int step;
}st,sd;

bool judge(int x, int y)
{
	if(x<0||x>=n||y<0||y>=m||vis[x][y] == 1 || mp[x][y] == '#')
		return false;
	return true;
}

void bfs(int a,int b)
{
    queue<node>q;
    node ss;
    //ss.x=0;
   // ss.y=0;
    memset(vis,0,sizeof(vis));
    //vis[a][b]=1;
    q.push((node){a,b,0});
    while(!q.empty())
    {
       // q.pop();
       st=q.front();
       q.pop();
       //printf("(%d, %d)\n",st.x,st.y);
       if(mp[st.x][st.y]=='@')
       {
           res[st.x][st.y]+=st.step;
       }
       for(int i=0;i<4;++i)
        {
            int xx=st.x+dir[i][0];
            int yy=st.y+dir[i][1];

            if(judge(xx,yy))
            {
               // printf("(%d, %d)\n",xx,yy);
               // sd.x=xx;
               // sd.y=yy;
                vis[xx][yy]=1;
                q.push((node){xx,yy,st.step+1});
            }




        }

    }

     return ;


}

//void print(int x,int y)
//{
//    if(!x&& !y)
//    {
//         printf("(0, 0)\n");
//         return ;
//    }
//
//
//    for(int i=0;i<4;++i)
//    {
//        int xx=x+dir[i][0];
//        int yy=y+dir[i][1];
//        if(xx>=0 &&xx<5 &&yy>=0&&yy<5 &&vis[xx][yy]==vis[x][y]-1)
//        {
//            print(xx,yy);
//            printf("(%d, %d)\n",x,y);
//            return ;
//        }
//
//    }
//
//
//}

int main()
{
    int s1x,s1y,s2x,s2y;
	while(scanf("%d %d", &n, &m)!=EOF)
	{
		for(int i=0; i<n; i++)
		{
			scanf("%s", mp[i]);
			for(int j=0; j<m; j++)
			{
				if(mp[i][j] == 'Y')
				{
					s1x = i;
					s1y = j;
				}
				if(mp[i][j] == 'M')
				{
					s2x = i;
					s2y = j;
				}
			}
		}
		memset(res, 0, sizeof(res));

		bfs(s1x, s1y);
		bfs(s2x, s2y);

		int ans = INF;
		for(int i=0;i<n;i++)
			for(int j=0; j<m; j++)
			{
				if(mp[i][j] == '@' && res[i][j] != 0)
				{
					ans = min(ans, res[i][j]);
				}
			}
		cout<<ans*11<<endl;
	}
	return 0;
}


 

### HDU 1682 Problem Explanation and Solution HDU 1682 is titled "Find a way". This problem involves finding the shortest path in a grid with specific constraints. The grid contains obstacles, and the task is to determine the minimum number of steps required to reach the destination from the starting point while avoiding obstacles[^5]. #### Problem Description The input consists of multiple test cases. Each test case includes: - A grid size `N x M`. - A grid where each cell is either empty (denoted by '.') or blocked (denoted by '#'). - The starting position `(x1, y1)` and the destination position `(x2, y2)`. The goal is to find the shortest path from the start to the destination, moving only up, down, left, or right, and avoiding blocked cells. #### Approach This problem can be solved using **Breadth-First Search (BFS)**, which is ideal for finding the shortest path in an unweighted graph. BFS ensures that the first time a node is visited, it is reached via the shortest possible path from the source. Here is a step-by-step explanation of the algorithm: - Represent the grid as a 2D array. - Use a queue to store the current position and the number of steps taken to reach it. - Mark visited cells to avoid revisiting them. - Expand the search in all four directions (up, down, left, right) at each step. - If the destination is reached, output the number of steps. Otherwise, if no path exists, output -1. #### Implementation Below is a Python implementation of the solution: ```python from collections import deque def solve(): T = int(input()) # Number of test cases results = [] for _ in range(T): N, M = map(int, input().split()) # Grid dimensions grid = [input().strip() for _ in range(N)] x1, y1, x2, y2 = map(int, input().split()) # Start and end positions # Adjust for zero-based indexing x1 -= 1; y1 -= 1; x2 -= 1; y2 -= 1 # BFS Initialization queue = deque([(x1, y1, 0)]) # (current_x, current_y, steps) visited = [[False] * M for _ in range(N)] visited[x1][y1] = True # Directions: up, down, left, right directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] found = False while queue: cx, cy, steps = queue.popleft() if cx == x2 and cy == y2: results.append(steps) found = True break for dx, dy in directions: nx, ny = cx + dx, cy + dy if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny] and grid[nx][ny] == '.': visited[nx][ny] = True queue.append((nx, ny, steps + 1)) if not found: results.append(-1) for result in results: print(result) # Example Input/Output # Input: # 1 # 3 3 # ... # .## # ... # 1 1 3 3 # Output: # 4 ``` #### Key Points - BFS guarantees the shortest path in an unweighted grid. - Visited cells are marked to prevent cycles and redundant computations. - The algorithm terminates early if the destination is reached.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值