《算法零基础100讲》(第3讲) 矩阵_英雄哪里出来-优快云博客
1-7已经解出 8-9太难了不会
第二题:1582. 二进制矩阵中的特殊位置
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 curr = mat[i][j] == 1;
rowCnt[i] += curr;
colCnt[j] += curr;
}
}
int res = 0;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
if (mat[i][j] == 1 && rowCnt[i] == 1 && colCnt[j] == 1)
{
++res;
}
}
}
return res;
他这里给的题解是建立了两个数组,rowcnt和colcnt,这两个数组是分别记录第i行的元素为1的个数,和第j列的元素唯一的个数,当
mat[i][j] == 1 && rowCnt[i] == 1 && colCnt[j] == 1
说明这一行这里一列只有一个元素等于1加上mat[i][j]==1就可以确定当前元素是特殊元素了。
我给的是遍历每个等于1的元素,然后再通过判断当前元素的行和列是否只有一个元素等于1,差不多,但是题解的利用两个数组记录更加有灵性。
第三题:832. 翻转图像
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
for(int i=0 ; i!=image.size() ; ++i){
int left=0 , right=image[0].size() - 1;
while(left<=right){
if(left == right){
image[i][left]^=1;
}
if(image[i][left] == image[i][right]){
image[i][left] ^= 1;
image[i][right] ^= 1;
}
++left;
--right;
}
}
return image;
法一:
翻转再反转矩阵,这里利用的这个特殊性。
如果image[i][left] != image[i][right],即1,0,交换就是0,1再反转还是1,0和原来值是相同的,也就可以不需要改变。
如果image[i][left] == image[i][right],那就不需要交换了,只需要进行反转即可,利用了位运算符^
当lef == right时,只需要进行反转,同样进行位运算
法二:
开辟一个数组,trans[i][j] == image[i][col-j-1],也可,但是浪费了内存
第四题: 48. 旋转图像
int row = matrix.size();
int col = matrix[0].size();
//右上左下对角线翻转
for(int x = 0 ; x!=row ; ++x){
for(int y = 0 ; y!=x ; ++y){
swap(matrix[x][y] , matrix[y][x]);
}
}
//左右翻转
for(int i=0 ; i!=row ; ++i){
int left = 0 , right = col-1;
while(left<right){
swap(matrix[i][left] , matrix[i][right]);
++left;
--right;
}
}
旋转一个矩阵有两种方法:case1 左下,右上对角线交换,再左右翻转
case2 左上,右下对角线交换,再上下翻转