Leetcode 1030.距离顺序排列矩阵单元格

在这里插入图片描述
思路: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;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值