《仨》 简单算法--2.DFS和BFS+3.位运算

113 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

2.DFS和BFS

 import java.io.*;
 import java.util.*;
 ​
 public class Main{
     static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
     static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
     static int[][] map = new int[10][10];
     static int[][] vis = new int[30][30];
     static int[][] dis = {{-1,0},{1,0},{0,-1},{0,1}};
     static int n,m,res = 0;
     static Node[] node = new Node[50];
     public static class Node{
         int x;
         int y;
         int pre;
         public Node(int x,int y,int pre) {
             this.x = x;
             this.y = y;
             this.pre = pre;
         }
         public Node() {
             
         }
     }
     public static boolean judge(int x1,int y1) {
         if(x1 < 0 || x1 >= m || y1 < 0 || y1 >= n || map[x1][y1] != 0 || vis[x1][y1] == 1)
             return true;
         return false;
     }
     static int bfs() {
         int x = 0;
         int y = 0;
         node[0] = new Node(0,0,0);
         vis[0][0] = 1;
         int head = 0;
         int tail = 1;
         while(head < tail) {
             x = node[head].x;
             y = node[head].y;
             for(int i = 0; i < 4; ++i) {
                 int x1 = x + dis[i][0];
                 int y1 = y + dis[i][1];
                 if(judge(x1,y1)) continue;
                 vis[x1][y1] = 1;
                 node[tail++] = new Node(x1,y1,head);
                 if(x1 == m - 1 && y1 == n - 1)
                     break;
             }
             ++ head;
         }
         return tail - 1;
 ​
         
     }
     public static void main(String[] args) throws Exception{
         String[] s = null;
         int i = 0;
         int pre = 0;
         Stack<Node> stack = new Stack<Node>();
         for(i = 0; i < 5; ++i) {
             s = in.readLine().split(" ");
             for(int j = 0; j < s.length; ++j) {
                 map[i][j] = Integer.parseInt(s[j]);
             }
         }
         n = 5;
         m = s.length;
         pre = bfs();
         while(pre != 0) {
             Node temp = node[pre];
             stack.push(new Node(temp.x,temp.y,temp.pre));
             pre = temp.pre;
         }
         stack.push(new Node(0,0,0));
         while(!stack.isEmpty()) {
             Node temp = stack.pop();
             out.write("(" + temp.x + ", " + temp.y + ")" + "\n");
         }
         in.close();
         out.close();
     }
 ​
 }

3.位运算

位运算符无疑就是那几个

| & 与

| | 或

|^异或

|~取反

|<<左移运算符

|>>右移运算符

位运算的重要应用

  1. (n >> k) & 1 取出整数n在二进制表示下的第k位(个位是第0位)
  2. n & ((1 << k) -1) 取出整数n在二进制表示下的第0~k-1位
  3. n ^ (1 << k) 把整数n在二进制表示下的第k位取反
  4. n | (1 << k) 把整数n在二进制表示下的第k位赋值为1
  5. n & (~(1 << k)) 把整数n在二进制表示下的第k为赋值为0
  6. a / 2 = a >> 1 ,且有 (a + b) / 2 = a + b >> 1
  7. 判断奇偶,我们知道奇数的第0位为1,偶数的第0位为1,则有 if(n & 1 == 1) write.out("奇数");else out.write("偶数"); \