穿越雷区

题目描述
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.Scanner; public class Main {
// 下一步的方向,分别为:上,下,左,右
static int[][] dir = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };
// 答案
static int ans = Integer.MAX_VALUE; public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
String[][] map = new String[n][n];
// 1代表访问过,0代表未访问过
int[][] visit = new int[n][n];
// A的行号
int x = 0;
// A的列号
int y = 0;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = s.next();
if (map[i][j].equals("A")) {
x = i;
y = j;
}
}
}
dfs(map, visit, x, y, 0);
System.out.println(ans);
s.close();
} public static void dfs(String[][] map, int[][] visit, int row, int col, int step) {
if (map[row][col].equals("B")) {
if (step < ans)
ans = step;
return;
}
visit[row][col] = 1;
for (int i = 0; i < dir.length; i++) {
// 下一步行号
int nextRow = row + dir[i][0];
// 下一步列号
int nextCol = col + dir[i][1];
if (nextRow < 0 || nextRow >= map.length || nextCol < 0 || nextCol >= map.length)
continue;
if (visit[nextRow][nextCol] == 0) {
visit[nextRow][nextCol] = 1;
if (!map[nextRow][nextCol].equals(map[row][col]))
dfs(map, visit, nextRow, nextCol, step + 1);
// 回溯
visit[nextRow][nextCol] = 0;
}
}
}
}

最新文章

  1. [LeetCode] Bulb Switcher 灯泡开关
  2. WinForms中的Label的AutoSize属性
  3. ACM训练计划建议(写给本校acmer,欢迎围观和指正)
  4. Linux-以指定用户运行redis
  5. HDU 5745 La Vie en rose
  6. HDU-4681 String 枚举+DP
  7. jmeter参数化数据(_csvread函数、用户自定义变量等)
  8. (转载)vsftpd简易配置
  9. Hdu 1856(离散化+并查集)More is better
  10. ios面试汇总
  11. Eclipse安装与搭建Maven
  12. Hadoop 源码分析(二四)FSNamesystem
  13. access数据库:怎么直接从access里把数据里同样的文字替换成空字符&amp;quot;&amp;quot;
  14. 使用cocoapods install友盟时报错Error installing UMengAnalytics
  15. source.list
  16. 基于嵌入式操作系统VxWorks的多任务并发程序设计(1)――基本概念
  17. 剑指Offer——网易笔试题+知识点总结
  18. ORACLE 12c RAC的常用管理命令
  19. DMA(直接存储器存取)
  20. python数据结构-如何根据字典中值的大小对字典项排序

热门文章

  1. ZOOM火速收购加密公司Kaybase 能否补齐安全短板?
  2. linux 修改时间同步到BIOS
  3. Python --函数学习1
  4. 我的第一篇博客-学习书写markdown
  5. DOM的使用
  6. react中控制元素的显示与隐藏
  7. zz 通过INFORMATION_SCHEMA.INNODB_TRX、INNODB_LOCKS、INNODB_LOCK_WAITS 三个表获取事务与锁的信息
  8. spring源码解析-ApplicationContext解析
  9. Spring Boot 教程 (3) - RESTful
  10. vue项目报错Missing space before function parentheses的问题