843. Guess the Word

这种题目,一般使用minMax的做法。
下面是code, 一定要注意多写成小函数,这样比较逻辑清楚不容易lost。

class Solution {
    public void findSecretWord(String[] wordlist, Master master) {
        int N = wordlist.length;
        int[][] graph = buildGraph(wordlist);
        
        List[] options = new ArrayList[1];
        options[0] = new ArrayList<>();
        for (int i = 0; i < N; i++) options[0].add(i);
        int cnt = 0;
        int feedback = -1;
        int cand = findNextCand(-1, feedback, options, wordlist, graph);
        while (true) {
            feedback = master.guess(wordlist[cand]);
            if (feedback == 6) break;
            cand = findNextCand(cand, feedback, options, wordlist, graph);
            cnt++;
            if (cnt > 10) break;
        }
    }
    private int findNextCand(int cand, int feedback, List[] options, String[] wordlist, int[][] graph) {
        if (feedback != -1 ) {
            List nextOption = new ArrayList<>();
            for (int next : options[0]) {
                if (graph[next][cand] == feedback) {
                    nextOption.add(next);
                }
            }
            options[0] = nextOption;
         }
        int nextCand = -1;
        int nextMax = Integer.MAX_VALUE;
        for (int next : options[0]) {
            int minMax = findMinMax(next, options[0], graph);
            if (minMax < nextMax) {
                nextMax = minMax;
                nextCand = next;
            }
        }
        return nextCand;
    }
    private int findMinMax(int next, List options, int[][] graph) {
        int[] histogram = new int[7];
        for (int op : options) {
            histogram[graph[next][op]]++;
        }
        return arrayMax(histogram);
    }
    private int arrayMax(int[] array) {
        int ans = 0;
        for (int n : array) ans = Math.max(ans, n);
        return ans;
    }
    
    private int[][] buildGraph(String[] wordlist) {
        int N = wordlist.length;
        int[][] graph = new int[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = i; j < N; j++) {
                int match = findMatch(wordlist[i], wordlist[j]);
                graph[i][j] = match;
                graph[j][i] = match;
            }
        }
        return graph;
    }
    private int findMatch(String w1, String w2) {
        int cnt = 0;
        for (int i = 0; i < w1.length(); i++) {
            if (w1.charAt(i) == w2.charAt(i)) cnt++;
        }
        return cnt;
    }
}

你可能感兴趣的:(843. Guess the Word)