1、矩阵中的路径
思路:题目很容易理解,给你一个字符串和一个字符矩阵,判断这个字符串是否在矩阵中。
- 我们先用一个标志数组来判断该位置是否被访问过。1代表访问过,0表示没有
- 求出元素的在数组的位置,index=i*cols+j;如果我们要用递归,那终止条件就是i,j小于0,要么就是i,j越界(超出cols和rows的范围),要么就是str[k]和数组元素不相等,要么就是数组的这个位置之前访问过。当遍历到字符串的最后一个元素的时候返回true;
- 需要注意的是,当这个格子的上下左右都不通时,要将这个位置归位,返回上一个格子,继续执行后面的。(我们走格子的方向是,左右上下)
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
int* flag=new int[strlen(matrix)];
memset(flag,0,strlen(matrix));
int k=0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(helper(matrix, rows, cols, str,i,j,0,flag))
return true;
}
}
return false;
}
bool helper(char* matrix,int rows,int cols,char* str,int i,int j,int k,int* flag)
{
int index=i*cols+j; //第几个元素
if(i<0||j>=cols||i>=rows||j<0||str[k]!=matrix[index]||flag[index]==1)
return false;
if(k==strlen(str)-1)
return true;
flag[index]=1;
if( helper(matrix, rows, cols, str,i-1,j,k+1,flag)
||helper(matrix, rows, cols, str,i+1,j,k+1,flag)
||helper(matrix, rows, cols, str,i,j-1,k+1,flag)
||helper(matrix, rows, cols, str,i,j+1,k+1,flag))
return true;
flag[index]=0;
return false;
}
};
2、顺时针打印矩阵(打印螺旋矩阵)
思路:定义四个变量,存放矩阵四个角的边界值。按照右下左上的顺序打印,就像这个样子的:
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix)
{
vector<int> temp;
int col=matrix[0].size(); //列
int row=matrix.size(); //行
if(row==0||col==0)
return temp;
int top=0;
int right=col-1;
int left=0;
int bottom=row-1;
while(top<=bottom&&left<=right)
{
//右
for(int i=left;i<=right;i++)
{
temp.push_back(matrix[top][i]);
}
//下
for(int i=top+1;i<=bottom;i++)
{
temp.push_back(matrix[i][right]);
}
//左
for(int i=right-1;i>=left&&top<bottom;i--)
{
temp.push_back(matrix[bottom][i]);
}
//上
for(int i=bottom-1;i>top&&right>left;i--)
{
temp.push_back(matrix[i][top]);
}
bottom--;right--;left++;top++;
}
return temp;
}
};