43ms C++ solution--concise and easy to understand


  • 0
    S

    class Solution {
    public:
    int shortestDistance(vector<vector<int>>& grid) {
    if (grid.empty() || grid[0].empty()) {
    return -1;
    }
    int m = grid.size(), n = grid[0].size(), res = INT_MAX, target = 0;
    vector<vector<int>> sum(m, vector<int>(n, 0));
    vector<vector<int>> dirs{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
    if (grid[i][j] == 1) {
    vector<vector<int>> dist(m, vector<int>(n, 0));
    queue<pair<int, int>> q;
    q.push(make_pair(i, j));
    while (!q.empty()) {
    int x = q.front().first;
    int y = q.front().second;
    q.pop();
    for (auto &dir : dirs) {
    int nx = x + dir[0];
    int ny = y + dir[1];
    if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == target) {
    q.push(make_pair(nx, ny));
    --grid[nx][ny];
    dist[nx][ny] = dist[x][y] + 1;
    sum[nx][ny] += dist[nx][ny];
    }
    }
    }
    --target;
    }
    }
    }
    for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
    if (grid[i][j] == target) {
    res = min(res, sum[i][j]);
    }
    }
    }
    return res == INT_MAX ? -1 : res;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.