题目:
在n行n列的字符串中,找到一个从a到z的连线,并输出,其余字符用“-”代替
肯定得先遍历,逐字判断,然后判断这个char的上下左右
整两个公有string[n],一个叫ans,一个叫res
这两个都用“-”填上n行n列;
然后就想到递归了,用ascii码,从97的a开始,判断正确就+1(b),错误就回溯-1(回到a);
把几种特殊情况列出来(上下左右的边,还有四个角)
正确就在ans里把这个字母插在对应的index上,然后删一个“-”;
最后判断到“z”了,就吧ans复制到res上;
再把res逐行输出;
总之就是可以过,但是找到了之后还是会把剩下的都遍历(没想到怎么优化)
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Solution
{
static string[] ans;
static string[] res;
static int aciinum=97;
static int n;
static void Main(string[] args)
{
n = int.Parse(Console.ReadLine());
string[] m = new string[n];
ans= new string[n];
res= new string[n];
for (int i = 0; i < n; i++)
{
m[i] = Console.ReadLine();
ans[i] = new string('-',n);
res[i] = new string('-',n);
//Console.Error.WriteLine(m[i]);
}
// Write an answer using Console.WriteLine()
// To debug: Console.Error.WriteLine("Debug messages...");
for(int i =0;i<n;i++){
for(int j =0;j<n;j++){
int a =i;
int b =j;
Search(m,a,b);
}
}
for(int i =0;i<n ;i++){
Console.WriteLine(res[i]);
}
}
static void Search(string[] m,int a,int b){
Console.Error.WriteLine(m[a][b] + "---" + (char)aciinum);
if(m[a][b] == (char)aciinum){
ans[a] = ans[a].Insert(b,m[a][b].ToString());
ans[a] = ans[a].Remove(b+1,1);
if(aciinum == 122){
aciinum = 96;
for(int i =0;i<n ;i++){
res[i] = ans[i];
}
return ;
}
aciinum ++;
if(a ==0 && b ==0) {
Search(m,a,b+1);
Search(m,a+1,b);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(a ==0 && b == n-1){
Search(m,a,b-1);
Search(m,a+1,b);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(a == n-1 && b ==0){
Search(m,a,b+1);
Search(m,a-1,b);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(a == n-1 && b ==n-1){
Search(m,a,b-1);
Search(m,a-1,b);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(a ==0 && b !=0 && b != n-1) {
Search(m,a,b-1);
Search(m,a,b+1);
Search(m,a+1,b);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(b ==0 && a !=0 && a != n-1) {
Search(m,a-1,b);
Search(m,a+1,b);
Search(m,a,b+1);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(a ==n-1 && b!=0 && b !=n-1) {
Search(m,a-1,b);
Search(m,a,b+1);
Search(m,a,b-1);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(b ==n-1 && a!=0 && a !=n-1) {
Search(m,a-1,b);
Search(m,a+1,b);
Search(m,a,b-1);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
if(b != 0 && b != n-1 && a != 0 && a != n-1) {
Search(m,a,b+1);
Search(m,a,b-1);
Search(m,a+1,b);
Search(m,a-1,b);
ans[a] = ans[a].Insert(b,"-");
ans[a] = ans[a].Remove(b+1,1);
if(aciinum>97) aciinum--;
}
}
return ;
}
}
结果: