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;
}
};