给出 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]);
}
}