清除行列 牛客网 程序员面试金典 C++ Python
题目描述
请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零。
给定一个N阶方阵int[]mat和矩阵的阶数n,请返回完成操作后的int[][]方阵(C++中为vector>),保证n小于等于300,矩阵中的元素为int范围内。
测试样例:
[[1,2,3],[0,1,2],[0,0,1]]
返回:[[0,0,3],[0,0,0],[0,0,0]]
C++
class Clearer { public: //run:33ms memory:864k vector<vector<int> > clearZero(vector<vector<int> > mat, int n) { vector<int> tmp; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (mat[i][j] == 0) tmp.push_back(i * n + j); for (unsigned i = 0; i < tmp.size(); i++){ int row = tmp[i] / n; int col = tmp[i] % n; for (int k = 0; k < n; k++){ mat[row][k] = 0; mat[k][col] = 0; } } return mat; } };Python
class Clearer: #run:1965ms memory:5696k def clearZero(self, mat, n): tmp = [] for i in range(n): for j in range(n): if mat[i][j] == 0: tmp.append(i*n+j) for i in range(len(tmp)): row = tmp[i] / n col = tmp[i] % n for k in range(n): mat[row][k] = 0 mat[k][col] = 0 return mat
转载于:https://www.cnblogs.com/vercont/p/10210313.html