POJ 3083.Children of the Candy Corn

题目:http://poj.org/problem?id=3083

AC代码(C++):

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>

#define INF 0xfffffff
#define MAXN 45

using namespace std;

char map[MAXN][MAXN];
bool vis[MAXN][MAXN];
int r,c;
int sx, sy;
int dir[][2] = {{-1,0},{0,1},{1,0},{0,-1}};//wdsa

struct point{
	int x,y,step;
};

int bfs(int x, int y) {
	queue<point> q;
	memset(vis, false, sizeof(vis));

	point start;
	start.x = x;
	start.y = y;
	start.step = 0;
	vis[x][y] = true;

	q.push(start);

	point node;
	while (!q.empty()) {
		node = q.front();
		q.pop();
		if(map[node.x][node.y]=='E'){
			return node.step + 1;
		}
		for(int i = 0; i < 4; i++){
			point tmp;
			tmp.x = node.x + dir[i][0];
			tmp.y = node.y + dir[i][1];
			if (tmp.x>=0&&tmp.y>=0&&tmp.x<r&&tmp.y<c&&map[tmp.x][tmp.y]!='#'&&vis[tmp.x][tmp.y]==false) {
				tmp.step = node.step + 1;
				q.push(tmp);
				vis[tmp.x][tmp.y] = true;
			}
		}
	}
	return -1;
}

int left(int x, int y){
	int step = 0;
	int dir0;//0123wdsa
	if(x==0)dir0 = 2;
	else if(x==r-1)dir0 = 0;
	else if(y==0)dir0 = 1;
	else if(y==c-1)dir0 = 3;
	while(1){
		if(map[x][y]=='E')break;
		int tmpx,tmpy;
		for(int i = 0; i < 4; i++){
			int dir1 = (dir0 + 3 + i)%4;
			tmpx = x + dir[dir1][0];
			tmpy = y + dir[dir1][1];
			if(tmpx>=0&&tmpy>=0&&tmpx<r&&tmpy<c&&map[tmpx][tmpy]!='#'){
				dir0 = dir1;
				break;
			}
		}
		x = tmpx;
		y = tmpy;
		step++;
	}
	return step + 1;
}

int right(int x, int y){
	int step = 0;
	int dir0;//0123wdsa
	if(x==0)dir0 = 2;
	else if(x==r-1)dir0 = 0;
	else if(y==0)dir0 = 1;
	else if(y==c-1)dir0 = 3;
	while(1){
		if(map[x][y]=='E')break;
		int tmpx,tmpy;
		for(int i = 0; i < 4; i++){
			int dir1 = (dir0 + 5 - i)%4;
			tmpx = x + dir[dir1][0];
			tmpy = y + dir[dir1][1];
			if(tmpx>=0&&tmpy>=0&&tmpx<r&&tmpy<c&&map[tmpx][tmpy]!='#'){
				dir0 = dir1;
				break;
			}
		}
		x = tmpx;
		y = tmpy;
		step++;
	}
	return step + 1;
}

int main()  
{  
    int t;
    cin>>t;
    while(t--){
    	cin>>c>>r;
    	for(int i = 0; i < r; i++)cin>>map[i];
    	for(int i = 0; i < r; i++){
    		for(int j = 0; j < c; j++){
    			if(map[i][j]=='S'){
    				sx = i;
    				sy = j;
    				break;
				}
			}
		}
    	cout<<left(sx,sy)<<' '<<right(sx,sy)<<' '<<bfs(sx,sy)<<endl;
	}
}
总结: 题意是要我们分别用三种方法走迷宫并记录距离. 最短距离不用说了, 最左的思路是: 记录每次前进的方向, 本次前进的方向就是从上次前进方向的左边开始顺时针找. 最右同理, 就是从上次前进方向的右边开始逆时针找. 这题TLE了一次, 因为第一次找最短路用的是dfs, 换了bfs就搞定了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值