剑指offer-12 矩阵中的路径

余生颓废 提交于 2020-02-24 13:43:19
#include <iostream>
struct Pos//路径点坐标结构体
{
 int x_pos;
 int y_pos;
};
char theArray[3][4] = {
 'a','b','t','g',
 'c','f','c','s',
 'j','d','e','h'
};
void location(char * target, Pos* path, int num, int total, int x, int y, bool* flag)//递归找点(target为给定的字符串,path为我们路径点坐标集合,num为当前已经匹配的字符数+1,total为一共需要匹配的字符数,x,y为坐标,flag为是否完全匹配成功。
{
 if (num > total)
 {
  *flag = true;
 }
 if (num <= total)
 {
  if (theArray[x][y] == target[num])
  {
   path[num].x_pos = x;
   path[num].y_pos = y;
   if(y > 0)//向左走
   {
    location(target, path, num + 1, total, x, y-1, flag);
   }
   if (y < 3)//向右走
   {
    location(target, path, num + 1, total, x, y+1, flag);
   }
   if (x < 2)//向下走
   {
    location(target, path, num + 1, total, x+1, y, flag);
   }
   
  }
 }
}
void search(char * target)
{
 bool flag = false;
 int times = strlen(target);
 Pos *path = new Pos[times];
 for (int i = 0; i < 4; i++)
 {
  location(target, path, 0, times - 1, 0, i, &flag);
 }
 if (flag)
 {
  for (int i = 0; i <times; i++)
  {
   std::cout << path[i].x_pos << "," << path[i].y_pos << std::endl;
  }
 }
 delete[] path;
}
int main()
{
 char test_arr[] = "bfcsh";
 search(test_arr);
 system("pause");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!