zoukankan      html  css  js  c++  java
  • 289. Game of Life

        /*
         * 289. Game of Life 
         * 2016-7-1 by Mingyang 
         * 这个题目的要求是in place,所以不能用另外一个matrix来表式,并且你改变的时候不能把下一个状态影响了
         * 所以这里用01来表示的话0可以变为3,1可以变为2
         * 然后记住这种找自己所在的九宫格,最好的方法就是设一个direction array,这样我们就可以找到
         * 然后再迭代整个array,把所有的数据拿到
         */
        int[][] dir = { { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, -1 }, { 0, 1 },
                { -1, -1 }, { -1, 0 }, { -1, 1 } };
        public void gameOfLife(int[][] board) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    int live = 0;
                    for (int[] d : dir) {
                        if (d[0] + i < 0 || d[0] + i >= board.length
                                || d[1] + j < 0 || d[1] + j >= board[0].length)
                            continue;
                        if (board[d[0] + i][d[1] + j] == 1
                                || board[d[0] + i][d[1] + j] == 2)
                            live++;
                    }
                    if (board[i][j] == 0 && live == 3)
                        board[i][j] = 3;
                    if (board[i][j] == 1 && (live < 2 || live > 3))
                        board[i][j] = 2;
                }
            }
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    board[i][j] %= 2;
                }
            }
        }
  • 相关阅读:
    创建线程方法&守护线程
    可见性
    线程池
    Callable创建线程
    使用java读取excel数据
    shell 中的操作符
    shell 中的特殊变量
    shell 变量定义使用
    golang 解码未知键的 json 字符串
    golang json 编码解码
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5635014.html
Copyright © 2011-2022 走看看