1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class Solution { public void wallsAndGates(int[][] rooms) { int INF = 2147483647; LinkedList<int[]> queue = new LinkedList<int[]>(); for (int i = 0; i < rooms.length; i++){ for (int j = 0; j < rooms[i].length; j++){ if (rooms[i][j] == 0) queue.add(new int[]{i,j}); } } int directions[][] = {{-1,0},{1,0},{0,1},{0,-1}}; while (!queue.isEmpty()){ int[] current = queue.poll(); for (int i = 0; i < 4; i++){ int newRow = current[0]+directions[i][0]; int newCol = current[1]+directions[i][1]; if (newRow >= 0 && newRow < rooms.length && newCol >= 0 && newCol < rooms[0].length &&rooms[newRow][newCol] == INF){ rooms[newRow][newCol] = rooms[current[0]][current[1]]+1; queue.add(new int[]{newRow, newCol}); } } } } } |
Saturday, December 5, 2015
[leetcode]Walls and Gates
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment