标签:hashset 二维 tac poll system ESS may 收集 inf
题目的英文版是这样的:
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
For example, given the 2D grid:
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
After running your function, the 2D grid should be:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
简单翻译成中文意思就是:-1所在的位置是墙,不能通过,0是门所在的位置,其他数字是可以通过的,要通过一个算法计算两个门之间的最短距离。概括一下就是这个是迷宫最有解的问题。
解:
提示:
1 二维矩阵可以看成是一个二维数组
2 BFS(广度优先算法)问题
思路:
这也是最常见的BFS的问题,需要不断遍历两个门相邻节点,然后判断是否可以通过,如果通过则可以继续对该点进行遍历,然后每对一个点遍历一次相邻的节点,都需要记录层数(这个层数就是距离);然后每次遍历都需要将遍历过的点用一个集合收集起来,以后遍历需要避开这些点,因为越早遍历到该点,说明用的距离是越短,所以第一次遍历到的点就是最短距离。
public static void wallsAndGates(int[][] a){
//先找到0所在位置(门所在位置)
for(int n=0;n<a.length;n++){
for(int m=0;m<a[0].length;m++){
if(a[n][m]==0){
int min = bfs(a,n,m);
//System.out.println(min);
if(min>0){
System.out.println(min);
return;
}
}
}
}
}
//遍历从这个门到另一个门的最短距离
public static int bfs(int[][] a,int n,int m){
Set<String> visits = new HashSet<String>();
Queue<String> queue = new LinkedList<String>();
queue.offer(n+""+m);
visits.add(n+""+m);
int count = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
String top = queue.poll();
char[] temp = top.toCharArray();
n = Integer.parseInt(""+temp[0]);
m = Integer.parseInt(""+temp[1]);
// System.out.println(a[n][m]);
//遍历该节点的相邻节点,如果
if(n>0){
int tmp = getCount(a,visits,n-1,m);
if(tmp==1){
count++;
return count;
}else if(tmp==2){
visits.add((n - 1) + "" + m);
queue.add((n - 1) + "" + m);
}
}
if(n<a.length-1){
int tmp = getCount(a,visits,n+1,m);
if(tmp==1){
count++;
return count;
}else if(tmp==2){
visits.add((n+1) + "" + m);
queue.add((n+1)+""+m);
}
}
if(m>0){
int tmp = getCount(a,visits,n,(m-1));
if(tmp==1){
count++;
return count;
}else if(tmp==2){
visits.add(n + "" + (m-1));
queue.add(n + "" + (m - 1));
}
}
if(m<a[0].length-1){
int tmp = getCount(a,visits,n,m+1);
if(tmp==1){
count++;
return count;
}else if(tmp==2){
visits.add(n + "" + (m+1));
queue.add(n + "" + (m + 1));
}
}
}
count++;
}
return -1;
}
/**
* 判断是否已访问的节点
*/
public static boolean findUsed(Set<String> visits,String visit){
if(visits.contains(visit)){
return true;
}
return false;
}
/**
*
*/
public static int getCount(int[][] a,Set<String> visits,int n,int m){
if(!findUsed(visits,n+""+m)) {
visits.add(n + "" + m );
if (a[n][m] == 0) {
return 1;
}else{
return 2;
}
}
return 0;
}
该方法效率不高,待优化!后续再优化更新
标签:hashset 二维 tac poll system ESS may 收集 inf
原文地址:https://www.cnblogs.com/yaphse-19/p/12029080.html