using System;
namespace WordPath
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class WordPath
{
private int count = 0;
public int countPaths(String[] grid, String find)
{
// 行
int i = 0;
// 列
int j = 0;
// 路径字符串索引
int index = 0;
// 循环起始位置次数
for (i = 0; i < grid.Length; i++)
{
for (j = 0; j < grid[i].Length; j++)
{
this.compare(grid, find, i, j, index);
}
}
if (count > 1000000000)
{
return -1;
}
return count;
}
private void compare(String[] grid, String find, int i, int j, int index)
{
if (count==-1)
{
return ;
}
if (index < find.Length - 1)
{
// 找到find指定索引处的字母
if (find[index] == grid[i][j])
{
// 正下方
if (i < grid.Length - 1 && find[index + 1] == grid[i + 1][j])
{
this.compare(grid, find, i + 1, j, index + 1);
}
// 正上方
if (i > 0 && find[index + 1] == grid[i - 1][j])
{
this.compare(grid, find, i - 1, j, index + 1);
}
// 正右方
if (j < grid[i].Length - 1 && find[index + 1] == grid[i][j + 1])
{
this.compare(grid, find, i, j + 1, index + 1);
}
// 正左方
if (j > 0 && find[index + 1] == grid[i][j - 1])
{
this.compare(grid, find, i, j - 1, index + 1);
}
// 右上方
if (i < grid.Length - 1 && j > 0
&& find[index + 1] == grid[i + 1][j - 1])
{
this.compare(grid, find, i + 1, j - 1, index + 1);
}
// 右下方
if (i < grid.Length - 1 && j < grid[i].Length - 1
&& find[index + 1] == grid[i + 1][j + 1])
{
this.compare(grid, find, i + 1, j + 1, index + 1);
}
// 左上方
if (i > 0 && j > 0
&& find[index + 1] == grid[i - 1][j - 1])
{
this.compare(grid, find, i - 1, j - 1, index + 1);
}
// 右下方
if (i > 0 && j < grid[i].Length - 1
&& find[index + 1] == grid[i - 1][j + 1])
{
this.compare(grid, find, i - 1, j + 1, index + 1);
}
}
}
else
{
count++;
System.Console.WriteLine(count);
if(count>1000000000)
count=-1;
return;
}
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
// string[] myChar = new string[]{ "ABC",
// "FED",
// "GHI"
// };
// string myString = "ABCDEFGHI" ;
// string[] myChar = new string[]{"ABC","FED","GAI"};
// string myString = "ABCDEA" ;
//
// string[] myChar = new string[]{"ABC","FED","GHI"};
// string myString = "ABCD" ;
//
// string[] myChar = new string[]{"AA","AA"} ;
// string myString = "AAAA" ;
//
// string[] myChar = new string[]{ "ABABA",
// "BABAB",
// "ABABA",
// "BABAB",
// "ABABA"
// } ;
// string myString = "ABABABBA" ;
//
string[] myChar = new string[]{"AAAAA","AAAAA","AAAAA","AAAAA","AAAAA"};
string myString = "AAAAAAAAAAA" ;
//
// string[] myChar = new string[]{"AB","CD"} ;
// string myString = "AA" ;
WordPath wp = new WordPath();
System.Console.WriteLine(wp.countPaths(myChar, myString ));
System.Console.ReadLine();
}
}
}