第十周LeetCode

来源:互联网 发布:淘宝50字好评 编辑:程序博客网 时间:2024/06/07 01:21

题目
难度 medium

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

Note:
1.The number of elements of the given matrix will not exceed 10,000.
2.There are at least one 0 in the given matrix.
3.The cells are adjacent in only four directions: up, down, left and right.

实现思路

可以用bfs实现,将ans[i][j]看成与最近的0的距离。先将矩阵元素不为0的位置值设为-1标记其未访问,然后将矩阵元素为0的坐标位置(i,j)入队。访问队列的队头,则其未被访问的相邻点(上下左右)的距离为ans[i][j]+1,并将其未被访问的相邻点坐标入队,直到队列为空。

实现代码

//储存坐标struct Node{        int x;        int y;        Node(int X, int Y) {            x = X;            y = Y;        }    };class Solution {    publicvector<vector<int>> updateMatrix(vector<vector<int> > &a) {        queue<Node> q ;        vector<vector<int>> ans = a ;        for (int i = 0; i < a.size(); i++) {            for (int j = 0; j < a[i].size(); j++) {                if (a[i][j] == 0) {                    q.push(Node(i, j));                } else {                    ans[i][j] = -1;                }            }        }        Node dire[4] = {Node(-1,0),Node(1,0),Node(0,-1),Node(0,1)};        while (!q.empty()) {            Node node = q.front();            int x = node.x;            int y = node.y;            q.pop();            for (int i = 0; i < 4; i++) {                int cur_x = x+dire[i].x;                int cur_y = y+dire[i].y;                //注意防止越界                if (cur_x >= 0 && cur_x < a.size()                     && cur_y >=0 && cur_y < a[cur_x].size() && ans[cur_x][cur_y]==-1) {                    ans[cur_x][cur_y] = ans[x][y]+1;                    q.push(Node(cur_x,cur_y));                }            }        }        return ans;    }};  
原创粉丝点击