BFS+思维


标题:穿越雷区

X星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。
某坦克需要从A区到B区去(A,B区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?

已知的地图是一个方阵,上面用字母标出了A,B区,其它区都标了正号或负号分别表示正负能量辐射区。
例如:
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -

坦克车只能水平或垂直方向上移动到相邻的区。

数据格式要求:

输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。
A,B都只出现一次。

要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1

例如:
用户输入:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -

则程序应该输出:
10

资源约定:
峰值内存消耗(含虚拟机) < 512M
CPU消耗  < 2000ms


请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。

所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意:不要使用package语句。不要使用jdk1.7及以上版本的特性。
注意:主类的名字必须是:Main,否则按无效代码处理。


 

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Node {
	int x, y, step, flag;
	public Node(int x, int y, int step, int flag) {
		super();
		this.x = x;
		this.y = y;
		this.step = step;
		this.flag = flag;
	}

	public Node() {
		step = 0;
	}

}

public class Main {
	static int ex, ey, bx, by;
	static int dx[]= {-1,1,0,0};
	static int dy[]= {0,0,-1,1};
	static int n;
	static char an[][] = new char[106][106];
	static int [][] vis=new int[106][106];
	 public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		n = cin.nextInt();
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				String s;
				vis[i][j]=0;
				s = cin.next();
				an[i][j] = s.charAt(0);
				if (an[i][j] == 'A') {
					bx = i;
					by = j;
				} else if (an[i][j] == 'B') {
					ex = i;
					ey = j;
				}
				//System.out.println(an[i][j]);
			}
			
		}
		//System.out.println(bx+"---"+by);
		int ans=bfs(bx, by);
		System.out.println(ans);
		//System.out.println(ex+"---"+ey);
	}

	static int bfs(int x, int y) {
		Queue<Node> que = new LinkedList<Node>();
		Node a = new Node();
		Node b = new Node();
		a.x = x;
		a.y = y;
		a.step = 0;
		que.add(a);
		while (!que.isEmpty()) {
			//System.out.println("---");
			a=que.peek();
			//System.out.println(a.x+"==="+a.y);
			que.poll();
			for(int i=0;i<4;i++)
			{
				b.x=a.x+dx[i];
				b.y=a.y+dy[i];
				b.step=a.step+1;
				if(b.x>=1&&b.y>=1&&b.x<=n&&b.y<=n&&vis[b.x][b.y]==0)
				{
						if(b.x==ex&&b.y==ey)
						{
							//System.out.println(b.x+"---"+b.y);
							return b.step;
						}
						if(an[b.x][b.y]!=an[a.x][a.y])
						{
							Node c=new Node();
							c.x=b.x;
							c.y=b.y;
							c.step=b.step;
							que.add(c);
							vis[b.x][b.y]=1;
							//System.out.println(c.x+"---"+c.y);
						}
				}
			}
		}
		return -1;
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值