【搜索】C051_LG_馬的遍歷(dfs 暴搜 / bfs)

一、Problem

有一個n*m的棋盤(1<n,m<=400),在某個點上有一個馬,要求你計算出馬到達棋
盤上任意一個點最少要走幾步

輸入格式

一行四個數據,棋盤的大小和馬的座標

輸出格式

一個n*m的矩陣,代表馬到達某個點最少要走幾步(左對齊,寬5格,不能到達則輸出-1)

3 3 1 1

0    3    2    
3    -1   1    
2    1    4    

二、Solution

方法一:dfs

n = 400,m = 400,會超時… 因爲存在重複遍歷,但無重複遍歷又不能保證值最小,因爲存在比較最小值。所以推薦用層序遍歷…

import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static class Solution {
		int R, C, sx, sy, g[][];
	int[][] d = new int[][] {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
		void print() {
			for (int i = 1; i <= R; i++) {
				for (int j = 1; j <= C; j++)
					System.out.printf("%-5d", g[i][j]);
				System.out.println();
			}
		}
		void dfs(int x, int y, int s) {
			g[x][y] = s;
			for (int k = 0; k < 8; k++) {
				int tx = x + d[k][0];
				int ty = y + d[k][1];
				if (tx >= 1 && tx <= R && ty >= 1 && ty <= C && (g[tx][ty] > s+1 || g[tx][ty] == -1)) {
					dfs(tx, ty, s+1);
				}
			}
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			R = sc.nextInt(); C = sc.nextInt(); sx = sc.nextInt(); sy = sc.nextInt();
			g = new int[R+1][C+1];
			for (int i = 1; i <= R; i++)
	        for (int j = 1; j <= C; j++) {
	            g[i][j] = -1;
	        }
			dfs(sx, sy, 0);
			print();
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

複雜度分析

  • 時間複雜度:O(...)O(...)
  • 空間複雜度:O(...)O(...)

方法二:bfs


複雜度分析

  • 時間複雜度:O()O()
  • 空間複雜度:O()O()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章