思路:BFS
把所有的坐标看作树的结点,距离相等的结点位于树的同一层
class Solution {
class node{
int x,y;
node(int xx,int yy){
x=xx;
y=yy;
}
}
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] res = new int[R*C][2];
boolean vis[][] = new boolean[R][C];
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
vis[i][j]=false;
Queue<node> q = new LinkedList<>();
int dx[]=new int[]{1,0,-1,0};
int dy[]=new int[]{0,1,0,-1};
q.add(new node(r0,c0));
int cnt=0;
vis[r0][c0]=true;
while(!q.isEmpty()){
node n = q.poll();
res[cnt][0]=n.x;
res[cnt][1]=n.y;
cnt++;
for(int i=0;i<4;i++){
int tx=n.x+dx[i];
int ty=n.y+dy[i];
if(tx>=0&&tx<R&&ty>=0&&ty<C&&!vis[tx][ty]){
vis[tx][ty]=true;
q.add(new node(tx,ty));
}
}
}
return res;
}
}