LeetCode:01 Matrix

542. 01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: 
Input:

0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0

 

Example 2: 
Input:

0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1

思路:直接深度优先遍历即可,注意记录下当前最短路径,有可能超时,以及对于返回值的处理,需要判断是否是最大INT32,否则+1会溢出。
 1 int getNearset(vector<vector<int>>& matrix, int i, int j,int m,int n,vector<vector<int>>&path,int dep,int mindep)
 2 {
 3     if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j]==2 || dep-2>mindep)
 4         return 0x7fffffff;
 5     if (path[i][j] != -1)
 6         return path[i][j];
 7     if (matrix[i][j] == 0)
 8         return path[i][j]=0;
 9     matrix[i][j] = 2;
10     int a = getNearset(matrix, i - 1, j, m, n, path,dep+1,0x7fffffff);
11     int b = getNearset(matrix, i + 1, j, m, n, path,dep+1,a);
12     int c = getNearset(matrix, i, j - 1, m, n, path,dep+1,min(a,b));
13     int d = getNearset(matrix, i, j + 1, m, n, path,dep+1,min(min(a,b),c));
14     int mindis = min(min(a,b), min(c,d));
15     matrix[i][j] = 1;
16     return mindis==0x7fffffff?0x7fffffff:mindis+1;
17 }
18 vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) 
19 {
20     vector<vector<int>>r;
21     int m = matrix.size();
22     if (m == 0)
23         return r;
24     int n = matrix[0].size();
25     vector<vector<int>>path(m, vector<int>(n, -1));
26     for (int i = 0; i < m; i++)
27         for (int j = 0; j < n; j++)
28             path[i][j] = getNearset(matrix, i, j, m, n, path,0,0x7fffffff);
29     return path;
30 }

 如果你有任何疑问或新的想法,欢迎在下方评论。

posted @ 2017-03-22 12:37  陆小风不写代码  阅读(412)  评论(0编辑  收藏  举报