LeetCode 542. 01 Matrix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012808902/article/details/78027369

542. 01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: 
Input:

0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0

Example 2: 
Input:

0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

1.题目

       给出由数字0和1组成的矩阵,找到每个数字1的格子距离所有数字0的格子最近的距离,并将每个数字1的格子中的数字改成对应的距离,并且输出改变后的矩阵。

2.思路

            问题的解空间是一个有向图G,G的顶点集合V的取值为0或1,且每个顶点的输出边只在符合条件下遵循“上,下,左,右”四个方向,我们要求的就是从0号顶点集合V0到1号顶点集合V1的最少的边数。
        我采取基于队列的广度优先的遍历策略,先将V0集合中所有的顶点入队,而后按出队顺序遍历每一个顶点的“可达顶点”,(可达顶点的值) > (出队顶点的值+1)时,就表明此时有更少的“边”可到达当前的”可达顶点”,并将其入队并在输出矩阵中更改起值为出队顶点的值+1(由此记录当前“可达顶点”的最短距离)。一直循环到队空为止。

3.代码

    class Point {
    	int x;
    	int y;
    	public Point(int x,int y){
    		this.x = x;
    		this.y = y;
    	}
    }
    
    public int[][] updateMatrix(int[][] matrix) {
    	int rows = matrix.length;
    	int cols = matrix[0].length;
        int[][] result = new int[rows][cols];
        
        Queue<Point> q = new LinkedList<Point>();
        List<Point> q1 = new ArrayList<Point>();
        
        for(int i=0;i<rows;i++){
        	for(int j=0;j<cols;j++){
        		if(matrix[i][j] == 0){
        			q.add(new Point(i,j));
        		}else{
        			q1.add(new Point(i,j));
        			result[i][j] = Integer.MAX_VALUE;//1号顶点的值为MAX,方便入队
        		}
        	}
        }
        
        Point up = new Point(0,1);
        Point down = new Point(0,-1);
        Point left = new Point(-1,0);
        Point right = new Point(1,0);
        Point[] direct = {up,down,left,right};
        
        while(!q.isEmpty()){
        	Point p = q.poll();
        	int x = p.x;
        	int y = p.y;
        	//0点所在的格子向四个方向走
        	for(int i=0;i<4;i++){
        		int nx = x + direct[i].x;
        		int ny = y + direct[i].y;
        		
        		//当0号点走到1号点,并且起距离小于原1号顶点记录的距离时
        		if(nx<rows && ny<cols && nx>=0 && ny>=0 
        				&& result[nx][ny]>result[x][y]+1){
        			result[nx][ny] = result[x][y] + 1;
        			q.add(new Point(nx,ny));
        		}
        		
        	}
        }
    	return result;
    }


猜你喜欢

转载自blog.csdn.net/u012808902/article/details/78027369