首页 > 其他 > 详细

o g 寻找最短

时间:2014-06-13 08:21:22      阅读:365      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣


给一个矩阵,每个格子上有三种可能,空房,阻碍物或者是保安,阻碍物不能进,空房
四个方向都能进,要写代码给每个空房标记其离最近的保安的距离,比如

000
BGG
B00

B表示障碍物,G表示保安,0表示空房,应该标记为

211
BGG
B11



import
java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class xddd { /** * @param args */ class Node{ int x, y; int step; Node(int x, int y, int step){ this.x = x; this.y = y; this.step = step; } } char[][] martrix ; int[][] stepArr = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; public xddd() { // TODO Auto-generated constructor stub martrix = new char[][]{{‘0‘,‘0‘,‘0‘},{‘B‘,‘G‘,‘G‘},{‘B‘,‘0‘,‘0‘}}; } public static void printmar(char[][] martrix){ for(int i=0; i<martrix.length;i++){ System.out.println(" "); for(int j=0; j<martrix[0].length; j++) System.out.print(martrix[i][j]); } } public int bfs(char[][] martrix, int ix, int iy){ int[][] visit = new int[3][3];//标记是否已经访问过 Node node = new Node(ix, iy, 0); Queue<Node> queue = new LinkedList<Node>(); queue.offer(node); int M = martrix.length; int N = martrix[0].length; while(!queue.isEmpty()){ Node head = queue.poll(); visit[head.x][head.y] = 1; for(int i = 0; i < 4; i++){ int x = head.x + stepArr[i][0]; int y = head.y + stepArr[i][1]; //exit if(x >= 0 && x < M && y >= 0 && y < N &&martrix[x][y] == ‘G‘){ return head.step+1; } //bfs if(x >= 0 && x < M && y >= 0 && y < N &&martrix[x][y] == ‘0‘ && visit[x][y] == 0){ System.out.println(x + " " +y + head.step); Node newNode = new Node(x, y, head.step + 1); queue.offer(newNode); } } } return -1; } public static void main(String[] args) { // TODO Auto-generated method stub xddd x = new xddd(); printmar(x.martrix); char[][] ret = new char[3][3]; for(int i=0; i<x.martrix.length;i++){ System.out.println(" "); for(int j=0; j<x.martrix[0].length; j++){ if(x.martrix[i][j] != ‘0‘) ret[i][j] = x.martrix[i][j]; else{ ret[i][j] = (char)(‘0‘ + x.bfs(x.martrix,i,j)); } } } printmar(ret); } }
bubuko.com,布布扣

 

o g 寻找最短,布布扣,bubuko.com

o g 寻找最短

原文:http://www.cnblogs.com/leetcode/p/3781154.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!