leetcode刷题. 542. 01 矩阵. bfs算法和动态规划算法复习

542. 01矩阵

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

1. 基于bfs算法的解法

vector> updateMatrix(vector>& matrix) {

	int xlen = matrix.size();
	int ylen = matrix[0].size();

    // 定义上下左右方向
    vector> dirs{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

	vector> output(xlen, vector(ylen, 0));
    vector> seen(xlen, vector(ylen, 0)); 

	queue> q;

    for(int i = 0; i < xlen; i++) {

        for(int j = 0; j < ylen; j++) {

            if(matrix[i][j] == 0) {

                q.push(pair(i, j));
                seen[i][j] = 1;
            }
        }
    }

    while(q.size()) {

        auto [i, j] = q.front();
        q.pop();

        for(int c = 0; c < 4; c++) {

            int ni = dirs[c][0] + i;
            int nj = dirs[c][1] + j;

            if(ni >= 0 && ni < xlen && nj >= 0 && nj < ylen && !seen[ni][nj]) {

                output[ni][nj] = output[i][j] + 1;
                q.push(pair(ni, nj));
                seen[ni][nj] = 1;
            }
        }
    }
    return output;
}

 

你可能感兴趣的:(【leetcode刷题】,【算法】)