LeetCode: Set Matrix Zeroes

一次过

 1 class Solution {

 2 public:

 3     struct node {

 4         int x;

 5         int y;

 6     };

 7     void setZeroes(vector<vector<int> > &matrix) {

 8         // Start typing your C/C++ solution below

 9         // DO NOT write int main() function

10         vector<struct node> S;

11         int m = matrix.size();

12         int n = matrix[0].size();

13         for (int i = 0; i < m; i++) {

14             for (int j = 0; j < n; j++) {

15                 if (!matrix[i][j]) {

16                     struct node tmp;

17                     tmp.x = i, tmp.y = j;

18                     S.push_back(tmp);

19                 }

20             }

21         }

22         for (int k = 0; k < S.size(); k++) {

23             struct node tmp = S[k];

24             for (int i = 0; i < m; i++) matrix[i][tmp.y] = 0;

25             for (int i = 0; i < n; i++) matrix[tmp.x][i] = 0;

26         }

27     }

28 };

 C#

 1 public class Solution {

 2     public class node {

 3         public int x;

 4         public int y;

 5         public node() {

 6             x = 0;

 7             y = 0;

 8         }

 9         public node(int x1, int y1) {

10             x = x1;

11             y = y1;

12         }

13     };

14     public void SetZeroes(int[,] matrix) {

15         List<node> S = new List<node>();

16         int m = matrix.GetLength(0);

17         int n = matrix.GetLength(1);

18         for (int i = 0; i < m; i++) {

19             for (int j = 0; j < n; j++) {

20                 if (matrix[i, j] == 0) S.Add(new node(i, j));

21             }

22         }

23         for (int k = 0; k < S.Count; k++) {

24             for (int i = 0; i < m; i++) matrix[i, S[k].y] = 0;

25             for (int i = 0; i < n; i++) matrix[S[k].x, i] = 0;

26         }

27     }

28 }
View Code

 

你可能感兴趣的:(LeetCode)