单词搜索(Java)

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCFD"
输出:true


示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true

示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "BFDS"
输出:false

package com.loo;

public class SearchWord {
	
	private static final int[] X = new int[] { 1 , 0 , -1 , 0};
	private static final int[] Y = new int[] { 0 , 1 , 0 , -1};

	public static void main(String[] args) {
		char[][] board = new char[][] {
			{'A' , 'B' , 'C' , 'E'},
			{'S' , 'F' , 'C' , 'S'},
			{'A' , 'D' , 'E' , 'E'}
		};
		String word = "ABCCFD";
		String word2 = "SEE";
		String word3 = "BFDS";
		System.out.println(existsSearchWord(word , board));
	}
	
	public static boolean existsSearchWord(String word , char[][] board) {
		if (word == null || word.length() == 0 || board == null || board.length == 0) {
			return false;
		}
		boolean[][] visited = new boolean[board.length][board[0].length];
		for (int x=0;x<board.length;x++) {
			for (int y=0;y<board[0].length;y++) {
				if (dfs(word , board , x , y , visited , 0)) {
					return true;
				}
			}
		}
		return false;
	}
	
	public static boolean dfs(String word , char[][] board , int x , int y , boolean[][] visited , int index) {
		if (word.charAt(index)!=board[x][y]) {
			return false;
		} else if (index == word.length()-1) {
			return true;
		}
		boolean result = false;
		visited[x][y] = true;
		for (int i=0;i<X.length;i++) {
			int tx = x + X[i];
			int ty = y + Y[i];
			if (tx<0 || tx>=board.length || ty<0 || ty >=board[0].length) {
				continue;
			}
			if (!visited[tx][ty]) {
				if (dfs(word , board , tx , ty , visited , index+1)) {
					result = true;
					break;
				}
			}
		}
		visited[x][y] = false;
		return result;
	}

}

 

Java单词簿程序设计可以用于创建一个简单的单词簿,用于存储和管理单词及其对应的释义。下面是一个简要的设计思路: 1. 定义一个Word类,其中包含属性word和meaning分别表示单词和释义。可以为这两个属性提供获取和设置方法。 2. 创建一个WordBook类,用于管理单词簿。该类可以包含一个动态数组,用于存储Word对象。 3. 在WordBook类中实现如下方法: - addWord方法:用于向单词簿中添加单词。该方法将接收Word对象作为参数,并将其添加到动态数组中。 - removeWord方法:用于从单词簿中删除指定的单词。该方法将接收一个字符串参数,表示要删除的单词。它会遍历动态数组,到与指定单词匹配的Word对象,并将其从数组中移除。 - searchWord方法:用于搜索指定单词的释义。该方法将接收一个字符串参数,并在动态数组中查与之匹配的Word对象。如果到匹配的单词,则返回其释义;否则返回空字符串。 - updateWord方法:用于更新指定单词的释义。该方法将接收两个参数,一个表示要更新的单词,另一个表示新的释义。它将遍历动态数组,到与指定单词匹配的Word对象,并更新其meaning属性。 4. 创建一个Java主类(可以命名为WordBookMain),在该类的主方法中实例化一个WordBook对象,并通过调用其方法来添加、删除、搜索和更新单词。 上述是一个简单的Java单词簿程序设计的设计思路。实际开发过程中,可以根据需求进行扩展和优化,增加更多的功能,如单词分类、数据持久化等。同时,还需考虑异常处理、界面设计等方面的问题,以实现一个完善的单词簿程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值