-->

Saturday, March 18, 2017

[LeetCode] 542. 01 Matrix

https://leetcode.com/contest/leetcode-weekly-contest-24/problems/01-matrix/

Solution:
This question seems not hard, but it is not easy to pass the OJ. One way to do it is kind of brute force bfs: for each element, gradually expand the searching range step by step until find the 0 element. But it is not fast enough.

One way to improve it is to think it in an opposite way: starting from elements with 0 value. Then gradually expand it: the first layer of neighbors should be 1; then the next layer should be 2; ... It's kind of using memorization. See code below:

Code:
  1. class Solution {
  2. public:
  3.     vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
  4.         vector<vector<int>> res = matrix;
  5.         if(!matrix.size() || !matrix.front().size()) return res;
  6.         int m = matrix.size(), n = matrix.front().size();
  7.         typedef pair<int, int> tp;
  8.         queue<tp> q;
  9.         for(int i=0; i<m; ++i){
  10.             for(int j=0; j<n; ++j){
  11.                 if(matrix[i][j]==0) q.push(tp(i, j));
  12.                 else res[i][j] = -1;
  13.             }
  14.         }
  15.         vector<tp> d={{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
  16.         while(q.size()){
  17.             tp tt = q.front();
  18.             int a = tt.first, b = tt.second;
  19.             q.pop();
  20.             for(auto t:d){
  21.                 int x = a + t.first, y = b + t.second;
  22.                 if(x>=0&&x<m&&y>=0&&y<n&&res[x][y]==-1){
  23.                     res[x][y] = res[a][b] + 1;
  24.                     q.push(tp(x,y));
  25.                 }
  26.             }
  27.         }
  28.         return res;
  29.     }
  30. };

No comments :

Post a Comment