普及练习场 深度优先搜索 单词方阵
来源:互联网 发布:网络营销师和编程 编辑:程序博客网 时间:2024/06/02 03:40
题目链接
题意理解
就是说,在一个方阵里面找”yizhong”,八个方向是
然后这题目我其实不知道怎么用dfs去写。。。 非要用dfs写,就是在search基础上优化一下,而不是得到了所有的字符串之后再进行判断结果。比如说,你得到的字符串已经是”yig”了,你知道肯定不对了,就可以退出dfs了,但是按照我的做法,你还得继续搞下去。
代码
import java.util.Scanner;public class Main { static int[][] changes = { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 }, { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 } }; static String yizhong = "yizhong"; static String[] string; static boolean[][] ok; static int n; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); ok = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ok[i][j] = false; } } string = new String[n]; for (int i = 0; i < n; i++) { string[i] = scanner.next(); } scanner.close(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (string[i].charAt(j) == 'y') { search(i, j); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (ok[i][j]) { System.out.print(string[i].charAt(j)); } else { System.out.print("*"); } } System.out.println(); } } static void search(int x, int y) { for (int t = 0; t < changes.length; t++) { String temp = ""; for (int i = 0; i < 7; i++) { int tempX = x + changes[t][0] * i; int tempY = y + changes[t][1] * i; if (0 <= tempX && tempX < n && 0 <= tempY && tempY < n) { temp += string[tempX].charAt(tempY); } } if(temp.equals(yizhong)) { for (int i = 0; i < 7; i++) { int tempX = x + changes[t][0] * i; int tempY = y + changes[t][1] * i; ok[tempX][tempY] = true; } } } }}
欢迎加入“不会算法一群菜鸟”,群号是⑥⑥①⑨②2025,这是我设置的一道很低的门槛用来阻止广告的。入群的验证暗号是:我爱编译原理
阅读全文