P1101单词方阵

题目链接:P1101
这个题(⊙o⊙)…, 蒟蒻表示不会用搜索写,没写出来,所以直接暴力
由题可知,我们有8个方向,8个方向满足条件的都需要输出来,问题就在他有可能是可以用重复的位置的,这个如果用搜索的话得想办法解决下这个问题,我不会
方法:
我们只需要寻找到头字符 也就是y找到这个字符后我们遍历他的8个方向看是不是满足yizhong这个字符顺序,满足的话记录下来即可
代码

import java.util.*;
public class Main {
	static int n;
	static char a[][];
	static boolean b[][];
	static char key[] = new String("yizhong").toCharArray();
	static int xx[] = new int[]{-1,-1,-1,0,0,1,1,1};
	static int yy[] = new int[]{-1,0,1,-1,1,-1,0,1};
	static void check(int x,int y){
		for(int i = 0;i < 8;i++){
			int j = 0;
			int p = x;
			int q = y;
			for(j = 1;j < 7;j++){
				if(p+xx[i]>=0 && p+xx[i]<n && q+yy[i]>=0 && q+yy[i]<n && (a[p+xx[i]][q+yy[i]] == key[j])){
					p = p+xx[i];
					q = q+yy[i];
				}
				else
					break;
			}
			if(j == 7){
				for(int k = 0;k < 7;k++){
					b[p][q] = true;
					p = p-xx[i];
					q = q-yy[i];
				}
			}
		}
	}
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		a = new char[n][n];
		b = new boolean[n][n];
		for(int i = 0;i < n;i++)
			for(int j = 0;j < n;j++)
				b[i][j] = false;
		for(int i = 0;i < n;i++)
			a[i] = sc.next().toCharArray();
		for(int i = 0;i < n;i++)
			for(int j = 0;j < n;j++)
				if(a[i][j] == 'y')
					check(i,j);
		for(int i = 0;i < n;i++){
			for(int j = 0;j < n;j++){
				if(b[i][j])
					System.out.print(a[i][j]);
				else
					System.out.print("*");
			}
			System.out.println();
		}
	}
}

发布了32 篇原创文章 · 获赞 5 · 访问量 862

猜你喜欢

转载自blog.csdn.net/shizhuba/article/details/104289288