class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int rows=mat.size();
int cols=mat[0].size();
int rowcnt[rows];
int colcnt[cols];
memset(rowcnt,0,sizeof(rowcnt));
memset(colcnt,0,sizeof(colcnt));
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
int falg=mat[i][j]==1?1:0;
rowcnt[i]+=falg;
colcnt[j]+=falg;
}
}
int res=0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(mat[i][j]==1&&colcnt[j]==1&&rowcnt[i]==1) res+=1;
}
}
return res;
}
};
翻转图像
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** flipAndInvertImage(int** image, int imageSize, int* imageColSize, int* returnSize, int** returnColumnSizes){
int i, j, col;
int **ret = (int **)malloc( sizeof(int *) * imageSize ); // imageSize为二维数组的第一维大小
*returnColumnSizes = (int *)malloc( sizeof(int) * imageSize ); // 返回结果的每行的列大小
for(i = 0; i < imageSize; ++i) {
col = imageColSize[i]; //第二维大小
ret[i] = (int *)malloc( sizeof(int) * col ); // 开辟大小
(*returnColumnSizes)[i] = col; //设置
for(j = 0; j < col; ++j) {
ret[i][j] = 1- image[i][ col-1-j ]; //
}
}
*returnSize = imageSize; //
return ret; //
}
c++
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (vector<int>& a : A) {
reverse(a.begin(), a.end());
for(int i=0;i<a.size();i++) a[i]=!a[i];
}
return A;
}
};
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
第一种:for(int i=0;i<matrix.size();i++){
for(int j=0;j<i;j++){
int temp=matrix[j][i];
matrix[j][i]=matrix[i][j];
matrix[i][j]=temp;
}
}//转置
for(vector<int>& a:matrix){
reverse(a.begin(),a.end());
}//左右颠倒
第二种:
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> res(n, vector<int>(m, 0));
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
res[j][i] = matrix[i][j];
}
}//求转置
matrix=res;
for(int i = 0; i<matrix.size(); ++i) {
for(int j = 0; j < matrix[0].size()/2; ++j) {
int temp =matrix[i][j];
matrix[i][j]= matrix[i][matrix[0].size()-1-j];
matrix[i][ matrix[0].size()-1-j ]=temp; //左右颠倒
}
}
}
};
转置
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> res(n, vector<int>(m, 0));//c++只能用vector
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[j][i] = matrix[i][j];
}
}
return res;
}
};