給出 R 行 C 列的矩陣,其中的單元格的整數坐標為 (r, c),滿足 0 <= r < R 且 0 <= c < C。
另外,我們在該矩陣中給出了一個坐標為 (r0, c0) 的單元格。
返回矩陣中的所有單元格的坐標,并按到 (r0, c0) 的距離從最小到最大的順序排,其中,兩單元格(r1, c1) 和 (r2, c2) 之間的距離是曼哈頓距離,|r1 - r2| + |c1 - c2|。(你可以按任何滿足此條件的順序返回答案。)
示例 1:
輸入:R = 1, C = 2, r0 = 0, c0 = 0
輸出:[[0,0],[0,1]]
解釋:從 (r0, c0) 到其他單元格的距離為:[0,1]
代碼
class Solution {public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {boolean [][] check=new boolean[R][C];check[r0][c0]=true;LinkedList<int[]> res=new LinkedList<>();int[][] dir=new int[][]{{0,1},{1,0},{-1,0},{0,-1}};Queue<int[]> queue=new LinkedList<>();queue.add(new int[]{r0,c0});while (!queue.isEmpty())//廣度優先搜索{int size=queue.size();for(int i=0;i<size;i++){int[] cur=queue.poll();res.add(cur);int x=cur[0],y=cur[1];for(int[] d:dir){int nextX=d[0]+x,nextY=d[1]+y;if(nextX>=0&&nextX<R&&nextY>=0&&nextY<C&&!check[nextX][nextY]){check[nextX][nextY]=true;queue.add(new int[]{nextX,nextY});}}}}return res.toArray(new int[res.size()][2]);}
}