[topcoder]NinePuzzle

http://community.topcoder.com/stat?c=problem_statement&pm=11225&rd=14427

http://apps.topcoder.com/wiki/display/tc/SRM+498

此题的暴力解法是一个BFS。BFS的话,要有Queue,如果是图的话,还要有Set来记录走过的状态。后面答案中会看到其实可以用贪心,就是只要输入和输出的各种颜色数量一样,就一定能变换过来,这个下回再表。

import java.util.*;

public class NinePuzzle

{

    public int getMinimumCost(String init, String goal)

    {

        int[][] arr = new int[10][];

        arr[0] = new int[]{1, 2};

        arr[1] = new int[]{0, 2, 3, 4};

        arr[2] = new int[]{0, 1, 4, 5};

        arr[3] = new int[]{1, 4, 6, 7};

        arr[4] = new int[]{1, 2, 3, 5, 7, 8};

        arr[5] = new int[]{2, 4, 8, 9};

        arr[6] = new int[]{3, 7};

        arr[7] = new int[]{3, 4, 6, 8};

        arr[8] = new int[]{4, 5, 7, 9};

        arr[9] = new int[]{5, 8};

        Queue<String> queue = new LinkedList<String>();

        HashSet<String> set = new HashSet<String>();

        set.add(goal);

        queue.offer(goal);

        int initStar = -1;

        for (int i = 0; i < init.length(); i++)

            if (init.charAt(i) == '*')

                initStar = i;

        int ans = Integer.MAX_VALUE;

        while (queue.size() != 0)

        {

            String s = queue.poll();

            char[] ca = s.toCharArray();

            int starPos = -1;

            for (int i = 0; i < ca.length; i++)

                if (ca[i] == '*') starPos = i;

                

            if (initStar == starPos)

            {

                int a = 0;

                for (int i = 0; i < s.length(); i++)

                {

                    if (initStar != i && ca[i] != init.charAt(i)) a++;

                }

                if (ans > a) ans = a;

            }

            for (int i = 0; i < arr[starPos].length; i++)

            {

                swap(ca, starPos, arr[starPos][i]);

                String tmp = new String(ca);

                if (!set.contains(tmp))

                {

                    queue.offer(tmp);

                    set.add(tmp);

                }

                swap(ca, starPos, arr[starPos][i]);

            }

        }

        return ans;

    }

    

    private void swap(char[] ca, int i, int j)

    {

        char tmp = ca[i];

        ca[i] = ca[j];

        ca[j] = tmp;

    }

}

  

你可能感兴趣的:(topcoder)