面试题12:矩阵中的路径
//上下左右递归,在看边界条件
#include<iostream>
#include<vector>
using namespace std;
//递归
bool haspathcore( char* m, int row, int col, int i, int j, const char* str, int& pathlen, bool* vis)
{
if (str[pathlen] == '\0')
{
return true;
}
bool haspath = false;
if (i >= 0 && i < row && j >= 0 && j < col && m[i*col + j] == str[pathlen] && !vis[i*col + col])
{
++pathlen;
vis[i*col + j] = true;
haspath = haspathcore(m, row, col, i + 1, j, str, pathlen, vis) ||
haspathcore(m, row, col, i - 1, j, str, pathlen, vis) ||
haspathcore(m, row, col, i, j + 1, str, pathlen, vis) ||
haspathcore(m, row, col, i, j - 1, str, pathlen, vis);
if (!haspath)
{
--pathlen;
vis[i*col + j] = false;
}
}
return haspath;
}
//主遍历
bool haspath( char* m, int row, int col, const char* str)
{
if (str == NULL || m == NULL || row < 1 || col < 1)
{
return false;
}
bool *vis = new bool[row*col];
memset(vis, 0, row*col);
int pathlen = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (haspathcore(m, row, col, i, j, str, pathlen, vis))
{
delete[] vis;
return true;
}
}
}
return false;
}
int main()
{
char test[] = "abtgcfcsjdeh";
char str[] = "bt";
bool resu = haspath(test, 3, 4, str);
cout << resu << endl;
getchar();
return 0;
}
面试题13:机器人的运动范围
思路:可以向上下左右移动 则递归(i+1,j),(i-1,j),(i,j+1),(i,j-1)
不能进入行列的数位之和相加>18 判断条件 i+j<18 而且没有访问过 !vis
得到行列之和 35 3行5列 3+5
#include<iostream>
using namespace std;
//得到行列数位之和
int getDigitSum(int num)
{
int sum = 0;
while (num > 0)
{
sum += num % 10;
num /= 10;
}
return sum;
}
//检查判断条件
bool check(int threshold, int row, int col, int i, int j, bool* vis)
{
if (i >= 0 && i < row&&j >= 0 && j < col&&getDigitSum(i) + getDigitSum(j) <= threshold && !vis[i*col + j])
{
return true;
}
return false;
}
//递归
int movingCountCore(int threshold, int row, int col, int i, int j, bool* vis)
{
int count = 0;
if (check(threshold, row, col, i, j, vis))
{
vis[i*col + j] = true;
count = 1 + movingCountCore(threshold, row, col, i + 1, j, vis)
+ movingCountCore(threshold, row, col, i - 1, j, vis)
+ movingCountCore(threshold, row, col, i, j + 1, vis)
+ movingCountCore(threshold, row, col, i, j - 1, vis);
}
return count;
}
//总的遍历
int movingCount(int threshold, int row, int col)
{
if (threshold < 0 || row <= 0 || col <= 0)
{
return 0;
}
bool* vis = new bool[row*col];
for (int i = 0; i < row*col; i++)
{
vis[i] = false;
}
int count = movingCountCore(threshold, row, col, 0, 0, vis);
delete[] vis;
return count;
}
int main()
{
int count = movingCount(5, 4, 4);
cout << "count= " << count << endl;
getchar();
return 0;
}