LeetCode 286. Walls and Gates


This method is not good but it is very straightforward.

#include <climits>
#include <vector>
#include <iostream>
using namespace std;

void wallsAndGates(vector< vector<int> >& matrix, int i, int j, vector< vector<bool> >& used, long long int& distance, long long int& minDis) {
  if((i < 0) || (i == matrix.size()) || (j < 0) || (j == matrix[i].size())) {
    return;
  } else {
    if(matrix[i][j] == 0) {
      minDis = min(minDis, distance);
      return;
    }
  }
  vector< vector<int> > direction {
    {0,  1},
    {0, -1},
    {-1, 0},
    {1, 0}};
  for(int k = 0; k < 4; ++k) {
    int next_i = i + direction[k][0];
    int next_j = j + direction[k][1];
    if(next_i >= 0 && next_i < matrix.size() && next_j >= 0 && next_j < matrix[i].size() && (matrix[next_i][next_j] != -1) && (used[next_i][next_j] == false)) {
      distance += 1;
      used[next_i][next_j] = true;
      wallsAndGates(matrix, next_i, next_j, used, distance, minDis);
      distance -= 1;
      used[next_i][next_j] = false;
    }
  }
}


void wallsAndGates(vector< vector<int> >& matrix) {
  if(matrix.size() == 0 || matrix[0].size() == 0) return;
  vector< vector<bool> > used(matrix.size(), vector<bool>(matrix[0].size(), false));
  for(int i = 0; i < matrix.size(); ++i) {
    for(int j = 0; j < matrix[i].size(); ++j) {
      if((matrix[i][j] == INT_MAX) && (used[i][j] == false)) {
        used[i][j] = true;
        long long int distance = 0;
        long long int minDistance = INT_MAX;
        wallsAndGates(matrix, i, j, used, distance, minDistance);
        used[i][j] = false;
        matrix[i][j] = minDistance;
      }
    }
  }
}


你可能感兴趣的:(LeetCode 286. Walls and Gates)