搜索

1.加了钥匙的搜索,很有趣

关键点就是用位来保存钥匙的状态

https://www.nowcoder.com/practice/e3fc4f8094964a589735d640424b6a47?tpId=90&tqId=30779&rp=1&ru=/ta/2018test&qru=/ta/2018test/question-ranking

private  int bfs(int i,int j,int N,int M,char G[][]) {
        Queue<Node> queue=new LinkedList<>();
        boolean visited[][][]=new boolean[N][M][1200];
        int dir[][]= {{0,1},{0,-1},{1,0},{-1,0}};
        Node node=new Node(i, j, 0, 0);
        queue.add(node);
        while(!queue.isEmpty()) {
            Node tmp=queue.poll();
            if(G[tmp.x][tmp.y]=='3') return tmp.step;
            for(int k=0;k<4;k++) {
                int x=tmp.x+dir[k][0];
                int y=tmp.y+dir[k][1];
                int key=tmp.key;
                if(x<0||x>=N||y<0||y>=M||G[x][y]=='0') continue;//表示走不通
                if(G[x][y]>='A'&&G[x][y]<='Z'&&((1<<(G[x][y]-'A')&tmp.key)==0)) continue;//遇到门而且走不通
                if(G[x][y]>='a'&&G[x][y]<='z')                  //遇到了钥匙,去保留这把钥匙
                    key=tmp.key|(1<<(G[x][y]-'a'));
                if(!visited[x][y][key]) {
                    visited[x][y][key]=true;
                    queue.add(new Node(x,y,key,tmp.step+1));
                }
            }
        }
        return -1;
}

 2.二维01数组求被0包围的连续的个数

https://leetcode.com/problems/number-of-islands/

private void bfs(char[][] grid, boolean[][] visited, int row, int col) {

        if (row >= 0 && row < grid.length // 行合法
            && col >= 0 && col < grid[0].length // 列合法
            && !visited[row][col] // 没有访问过
            && grid[row][col] == '1') { // 是岛上陆地
            visited[row][col] = true;
            //只有上下左右这几个位置连接才有用,对角是不能算的,做广度优先搜索
            bfs(grid, visited, row - 1, col);
            bfs(grid, visited, row, col + 1);
            bfs(grid, visited, row + 1, col);
            bfs(grid, visited, row, col - 1);
            
        }
    }
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        boolean[][] visited = new boolean[grid.length][grid[0].length];

        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                // 如果此位置没有被访问过,并且此位置是岛,就里德广度优先遍历
                if (!visited[i][j] && grid[i][j] == '1') {
                    result++;
                    bfs(grid, visited, i, j);
                }
            }
        }
        return result;
    }

 

posted @ 2019-03-28 11:16  LeeJuly  阅读(239)  评论(0)    收藏  举报