给一个矩阵,每个格子上有三种可能,空房,阻碍物或者是保安,阻碍物不能进,空房
四个方向都能进,要写代码给每个空房标记其离最近的保安的距离,比如
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); } }
原文:http://www.cnblogs.com/leetcode/p/3781154.html