ZOJ 1008 Gnome Tetravex

Hart is engaged in playing an interesting game, Gnome Tetravex, these days. In the game, at the beginning, the player is given n*n squares. Each square is divided into four triangles marked four numbers (range from 0 to 9). In a square, the triangles are the left triangle, the top triangle, the right triangle and the bottom triangle. For example, Fig. 1 shows the initial state of 2*2 squares.


Fig. 1 The initial state with 2*2 squares

The player is required to move the squares to the termination state. In the termination state, any two adjoining squares should make the adjacent triangle marked with the same number. Fig. 2 shows one of the termination states of the above example.


Fig. 2 One termination state of the above example

It seems the game is not so hard. But indeed, Hart is not accomplished in the game. He can finish the easiest game successfully. When facing with a more complex game, he can find no way out.

One day, when Hart was playing a very complex game, he cried out, "The computer is making a goose of me. It's impossible to solve it." To such a poor player, the best way to help him is to tell him whether the game could be solved. If he is told the game is unsolvable, he needn't waste so much time on it.


Input

The input file consists of several game cases. The first line of each game case contains one integer n, 0 <= n <= 5, indicating the size of the game.

The following n*n lines describe the marking number of these triangles. Each line consists of four integers, which in order represent the top triangle, the right triangle, the bottom triangle and the left triangle of one square.

After the last game case, the integer 0 indicates the termination of the input data set.


Output

You should make the decision whether the game case could be solved. For each game case, print the game number, a colon, and a white space, then display your judgment. If the game is solvable, print the string "Possible". Otherwise, please print "Impossible" to indicate that there's no way to solve the problem.

Print a blank line between each game case.

Note: Any unwanted blank lines or white spaces are unacceptable.


Sample Input

2
5 9 1 4
4 4 5 6
6 8 5 4
0 4 4 3
2
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
0


Output for the Sample Input

Game 1: Possible

Game 2: Impossible

开始随便写了个,然后超时了。。SHIT!!!

总体的思路就是,用空间换时间吧,毕竟爆内存还是很少的情况。

代码先建立了一个索引(三张map)

好处就是虽然搜索起来,仍然是线性的搜索,但是搜索长度减少了很多,而且无需判断。

所以要寻找符合某种情况的值,只要在map里取就好了,取出来的都是符合的

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Main{
    private static Squre[][] grid = null;
    private static List<Squre> squreList = new ArrayList<Squre>();
    private static Map<Integer, List<Squre>> leftMap = new HashMap<Integer, List<Squre>>();
    private static Map<Integer, List<Squre>> topMap = new HashMap<Integer, List<Squre>>();
    private static Map<Integer, List<Squre>> topAndLeftMap = new HashMap<Integer, List<Squre>>();
    private static Map<Integer, Squre> containMap = new HashMap<Integer, Squre>();
    private static int size = 0;
    private static boolean found = false;
    private static int totalSize = 0;
    public static void main(String[] args) {
        int gameCount = 0;
         Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            size = Integer.parseInt(scanner.nextLine());
            if (size == 0) {
                //stop the program......
                break;
            }
            //count the game...
            gameCount++;totalSize = size*size;
            for (int i = 0; i < totalSize; i++) {
                String[] params = scanner.nextLine().split(" ");
                Squre squre = new Squre(Integer.parseInt(params[0]), Integer.parseInt(params[1]),
                        Integer.parseInt(params[2]), Integer.parseInt(params[3]));
                if(containMap.containsKey(squre.allkey())){
                    Squre s = containMap.get(squre.allkey());
                    s.recover();
                } else {
                    containMap.put(squre.allkey(),squre);
                    squreList.add(squre);
                }
            }
            init();
            if(gameCount != 1){
                System.out.print("\n\n");
            }
            tryPosition(1);
            if(found){
                System.out.print("Game " + gameCount + ": Possible");
            } else {
                System.out.print("Game " + gameCount + ": Impossible");
            }
            found = false;
            squreList.clear();
            leftMap.clear();
            topMap.clear();
            topAndLeftMap.clear();
            containMap.clear();
        }
    }
    private static void init() {
        grid = new Squre[size][size];
        for (Squre s : squreList) {
            List<Squre> topList = topMap.get(s.getTop());
            if (topList == null) {
                // intilize the list in the map......
                topList = new ArrayList<Squre>();
                topMap.put(s.getTop(), topList);
            }
            topList.add(s);

            List<Squre> leftList = leftMap.get(s.getLeft());
            if (leftList == null) {
                // intilize the list in the map......
                leftList = new ArrayList<Squre>();
                leftMap.put(s.getLeft(), leftList);
            }
            leftList.add(s);

            List<Squre> leftAndTopList = topAndLeftMap.get(s.topLeftKey());
            if (leftAndTopList == null) {
                // intilize the list in the map......
                leftAndTopList = new ArrayList<Squre>();
                topAndLeftMap.put(s.topLeftKey(), leftAndTopList);
            }
            leftAndTopList.add(s);
        }
    }
    /**
     * try to find the position......
     */
    private static void tryPosition(int position) {
        int y = (position - 1) / size;
        int x = position % size == 0 ? size - 1 : position % size - 1;
        boolean top = true;
        boolean left = true;
        int topValue = -1;
        int leftValue = -1;
        // look for top value
        if (y == 0) {
            top = false;
        }
        if (x == 0) {
            left = false;
        }
        if (top) {
            // need to match the top
            topValue = grid[y - 1][x].getBottom();
        }
        if (left) {
            // need to match the left
            leftValue = grid[y][x - 1].getRight();
        }
        List<Squre> searchList = null;
        if (top && left) {
            // search both
            searchList = topAndLeftMap.get(topValue + leftValue*1000);
        } else if (top && !left) {
            // top value must match
            searchList = topMap.get(topValue);
        } else if (!top && left) {
            // left value must match
            searchList = leftMap.get(leftValue);
        } else {
            // no value needs to be match, the first grid......
            searchList = squreList;
        }
        if (searchList == null) {
            // no match list......
            return;
        }
        for(int i=0;i<searchList.size();i++){
            Squre squre = searchList.get(i);
            if(squre.getAvalibleCount() == 0){
                continue;
            }
            squre.select();
            grid[y][x] = squre;
            if(position == totalSize){
                found = true;
                return;
            }
            int nextPisition = position + 1;
            tryPosition(nextPisition);
            if(found){
                //if the result is found,just return...
                return;
            }
            grid[y][x] = null;
            squre.recover();
        }
    }
}


class Squre {
    public Squre(int top, int right, int bottom, int left) {
        this.top = top;
        this.left = left;
        this.right = right;
        this.bottom = bottom;
    }

    private int top;
    private int left;
    private int right;
    private int bottom;

    public int getTop() {
        return top;
    }

    public int getLeft() {
        return left;
    }

    public int getRight() {
        return right;
    }

    public int getBottom() {
        return bottom;
    }

    @Override
    public String toString() {
        return "[" + top + "," + right + "," + bottom + "," + left + "]";
    }
    
    public int getAvalibleCount() {
        return avalibleCount;
    }

    public void setAvalibleCount(int avalibleCount) {
        this.avalibleCount = avalibleCount;
    }
    public void recover(){
        avalibleCount++;
    }
    public void select(){
        avalibleCount--;
    }
    public Integer topLeftKey(){
        return top+left*1000;
    }
    public Integer allkey(){
        return top+right*10+bottom*100+left*1000;
    }
    private int avalibleCount =1;
    @Override
    public boolean equals(Object arg0) {
        if(!(arg0 instanceof Squre)){
            return false;
        }
        Squre s = (Squre)arg0;
        return this.top == s.getTop()
                && this.left == s.getLeft()
                && this.right == s.getRight()
                && this.bottom == s.getBottom();
    }
}

 1.9秒。。。不算很快。。看到个用c++。。30ms的。。真不知道是怎么搞得

猜你喜欢

转载自silentdusk.iteye.com/blog/1530789
ZOJ