算法期中 最近的0

Problem:

输入一个N*M的01矩阵A,对矩阵的每个位置,求至少经过多少步可以到达一个0. 每一步可以往上下左右走一格.

请为下面的Solution类实现解决这一问题的函数nearestZero,函数参数A为给出的01矩阵,A的行数和列数均不大于100. 函数的返回值是问题的答案.

例如:
A=
1 1 1
0 1 1
0 0 1

答案为
1 2 3
0 1 2
0 0 1

Code:

class Solution {
public:
    vector<vector<int>> nearestZero(vector<vector<int>>& A) {
        vector<vector<int>> dis;

        for (int i = 0; i < A.size(); i++) {
            vector<int> disOfOneRow;
            for (int j = 0; j < A[i].size(); j++) {
                if(A[i][j] == 0)
                    disOfOneRow.push_back(0);
                else {
                    disOfOneRow.push_back(BFS(A, i, j));
                }
            }
            dis.push_back(disOfOneRow);
        }
        return dis;
    }

    int BFS(vector<vector<int>>& A, int row, int col) {
        queueint, int>> cor;
        cor.push(make_pair(row, col));
        int visited[100][100];
        int count[100][100];
        count[row][col] = 0;
        for (int i =0; i<100;i++)
            for(int j=0; j<100;j++) {
                visited[i][j] = 0;
                count[i][j] = 0;
            }
        while (cor.size() != 0) {
            pair<int, int> next = cor.front();
            cor.pop();
            if (A[next.first][next.second] == 0)
                return count[next.first][next.second];
            visited[next.first][next.second] = 1;
            int nrow = next.first;
            int ncol = next.second;
            int adjrow[2] = {nrow-1, nrow+1};
            int adjcol[2] = {ncol-1, ncol+1};
            for (auto r : adjrow) {
                if (r>=0 && rif (visited[r][ncol] == 0) {
                        visited[r][ncol] = 1;
                        cor.push(make_pair(r, ncol));
                        count[r][ncol] = count[nrow][ncol] + 1;
                    }
                }
            }
            for (auto c : adjcol) {
                if (c>=0 && c0].size()) {
                    if (visited[nrow][c] == 0) {
                        visited[nrow][c] = 1;
                        cor.push(make_pair(nrow, c));
                        count[nrow][c] = count[nrow][ncol] + 1;
                    }
                }
            }
        }
    }
};                                 

你可能感兴趣的:(算法期中 最近的0)