【搜索】B053_LG_單詞方陣(dfs + 技巧)

一、Problem


二、Solution

方法一:dfs

  • 搜到 'y' 就 dfs
  • 在 dfs 中,對 8 個方向中的每一個方向都判斷一下,該單獨走某一個方向是否可匹配完 s,匹配不完整的可能有二:
    • 數組越界
    • 當前下標與 s 的當前下標不匹配
  • 匹配地完就將 res 數組標記爲該方向的一整條 s
import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
	static class Solution {
	    int N, dir[][] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
    	char[][] g, res;
    	boolean[] vis;
    	char[] s = "yizhong".toCharArray();
    	
		void dfs(int x, int y) {
			for (int k = 0; k < 8; k++) {
				boolean match = true;
				for (int i = 1; i <= 6; i++) {
					int tx = x + i * dir[k][0];
					int ty = y + i * dir[k][1];
					if (tx < 0 || tx >= N || ty < 0 || ty >= N || s[i] != g[tx][ty]) {
						match = false;
						break;
					}
				}
				if (!match)		
					continue;	
				for (int i = 0; i <= 6; i++) {
					int tx = x + i * dir[k][0], ty = y + i * dir[k][1];
					res[tx][ty] = g[tx][ty];
				}
			}
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			N = sc.nextInt();
			g = new char[N+1][N+1];
			res = new char[N+1][N+1];
			for (int i = 0; i < N; i++) {
				String s = sc.next();
				for (int j = 0; j < N; j++)
					g[i][j] = s.charAt(j);
			}
			for (int i = 0; i < N; i++) {
				for (int j = 0; j < N; j++)
				 	if (g[i][j] == 'y')
				 		dfs(i, j);
			}
			for (int i = 0; i < N; i++) {
				for (int j = 0; j < N; j++)
					System.out.print(res[i][j] == 0 ? "*" : res[i][j]);
				System.out.println();
			}
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

複雜度分析

  • 時間複雜度:O(1nlens)O(\sum_{1}^{n}len_s),字符串 s 的個數 × lenslen_s
  • 空間複雜度:O(...)O(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章